在2D数组中查找重复项 - 行和列

时间:2015-10-21 18:58:57

标签: c

我想知道如何单独找到重复项 - 行和列。

到目前为止,我认为我有这个排,没有真正测试过它。但我有点混淆如何以列方式查找2D数组的重复项?我需要实现2个函数,一个用于查找行的副本,另一个用于查找列的副本。

bool uniqueRow(int square[][MAX_SIZE], int sqrSize, int i) {

   int j;

   for(i = 0; i < sqrSize; ++i) {
      for(j = i; i < sqrSize && square[i][i] != square[i][j]; ++j) {

         if(square[i][i] == square[i][j])
            return false;

         else
            return true;
      }
   }

   return false;
}
bool uniqueCol(int square[][MAX_SIZE], int sqrSize, int i) {

   int j;

   for(i = 0; i < sqrSize; ++i) {
      for(j = i; i < sqrSize && square[i][i] != square[j][i]; ++j) {

         if(square[i][i] == square[j][i])
            return false;

         else 
            return true;
      }
   }
}

3 个答案:

答案 0 :(得分:1)

如果您不关心效率(您的代码已经在O(n ^ 2)中),请使用HashSet使用add(elem)方法向其添加元素,并查找重复项对于使用contains(elem)方法的2D矩阵中的每个元素。

如果HashSet中没有元素,则将其添加到HashSet中 - 不能存储重复项。

这就是你要找的东西吗?

答案 1 :(得分:1)

这是一个可以工作的循环示例:

int i, j, rowLenght = 6, colLenght = 6, arr[rowLenght][colLenght];
for(i = 0; i < rowLenght; ++i) {
   for(j = i; i < colLenght && arr[i][i] != arr[i][j]; ++j);

   if(arr[i][i] == arr[i][j])
     printf("We have mathch at arr[%d][%d] is same as arr[%d][%d]", i, i, i, j);
}

只需交换几个变量,你就可以匹配一个

int i, j, rowLenght = 6, colLenght = 6, arr[rowLenght][colLenght];
for(i = 0; i < rowLenght; ++i) {
  for(j = i; i < colLenght && arr[i][i] != arr[j][i]; ++j);

  if(arr[i][i] == arr[j][i])
    printf("We have mathch at arr[%d][%d] is same as arr[%d][%d]", i, i, j, i);
}

答案 2 :(得分:1)

在这里,请改为使用此代码:

//Assuming int a[][] contains all input elements,
//and that n is the number of rows and columns

for(int i=0; i<n; i++)
  {
    int tmp[n], size=0, dup=0;
    for(int j=0; j<n; j++){
      if(size>0)
        {
          int k=0;
          while(k<size)
            {
              //comparing each element of tmp with current row's(i) current(j) element
              if(a[j]==tmp[k])
                {
                  dup=1;
                  break;
                }
              else
                k++;
            }
          if(k==size&&k<n){ //updated here,
            tmp[k]=a[j];    //
            size++;         //and here, incrementing size
            }
        }
      if(dup==1)
        printf("Duplicate found");
    }
  }

这会将行的每个元素与包含该行的唯一元素的临时元素数组进行比较。您可以对列采用类似的方法。

相关问题