在数组中查找重复元素,无法正常工作

时间:2013-03-05 12:04:40

标签: c

朋友们,我有这个数组,我试图找出有多少元素是重复的,剩下的元素是什么。但问题是它显示出不同的结果。请检查

#include <stdio.h>
#include <stdlib.h>

#define SIZE 30

int const arr_1[SIZE] = {3,4,3,7,4,90,45,23,57,68,23,14,57,
                   34,20,39,18,3,2,23,45,67,89,68,12,34,56,78,3
                   };



int main()
{

  int i,j,yes=0, no=0;

  for(i=0;i<SIZE;i++)
  {
     for(j=0; j<SIZE; j++)
     {
        if(arr_1[i] == arr_1[j])

              yes++; 
         else 

           no++;   

     }

  }

  printf("temp: %d\t Not: %d\n",yes,no);

  system("PAUSE");
  return 0;
}

3 个答案:

答案 0 :(得分:0)

您的tempnot变量怎么样?你不能使用yesno吗?

实际上必须纠正algorythm:

for (i = 0; i < SIZE; i++)
{
    int notfound = 0;
    for (j = i + 1; j < SIZE; j++)
    {
        if (arr_1[i] == arr_1[j])
        {
            yes++; 
            notfound = 1; //found, no need to iterate anymore
            break;
        }
    }
    if (notfound == 0) //and we know that element isn't duplicate only here
        no++;
}

答案 1 :(得分:0)

问题是你要比较每对元素两次。例如,您正在比较arr_1[1] == arr_1[2],但稍后在循环中您还要比较arr_1[2] == arr_1[1],因此结果会计算两次。此外,您要将元素i与元素i进行比较,元素for(j=0; j<SIZE; j++) 将始终相同。要解决此问题,您应该更改:

for(j=i+1; j<SIZE; j++)

{{1}}

这样,第二个循环从第一个循环的当前索引开始,你只检查每对一次。

答案 2 :(得分:0)

 #include <stdio.h>
    #include <stdlib.h>

    int arr_1[30] = {3,4,3,7,4,90,45,23,57,68,23,14,57,34,20,39,18,3,2,23,45,67,89};
    int main()
    {

      int i,j,yes=0;
      for(i=0;i<23;i++)
      {
      yes=0;

         for(j=0; j<23; j++)
         {
            if(i==j){continue;}
            if(arr_1[i] == arr_1[j])
                yes++; 


         }
         if(yes==0)
             { printf("\n%d unique element",arr_1[i]);
              }
         else
              { printf("\n%d repeat %d time(s) " ,arr_1[i],yes);}

      }



  return 0;
}

enter image description here