4

我被告知下面的代码是 = O(MN) 但是,我想出了 O(N^2)。哪个是正确答案,为什么?

我的思考过程:嵌套 for 循环加上 if 语句 --> (O(N^2)+O(1)) + (O(N^2)+O(1)) = O(N^2)

谢谢

public static void zeroOut(int[][] matrix) { 
    int[] row = new int[matrix.length];
    int[] column = new int[matrix[0].length];
// Store the row and column index with value 0 
 for (int i = 0; i < matrix.length; i++)
   {
    for (int j = 0; j < matrix[0].length;j++) { 
       if (matrix[i][j] == 0) 
          {
            row[i] = 1;
            column[j] = 1; 
          }
   } 
  }
// Set arr[i][j] to 0 if either row i or column j has a 0 
for (int i = 0; i < matrix.length; i++)
 {
   for (int j = 0; j < matrix[0].length; j++)
      { 
        if ((row[i] == 1 || column[j] == 1)){
              matrix[i][j] = 0; 
           }
      } 
  }
}
4

1 回答 1

10

M 和 N 指的是什么?我的假设是它分别指的是“行”和“列”。如果是这样,那么等式就是 O(MN),因为你循环了 M 次 N 次。

如果行和列相等,O(N^2) 将是正确的。

于 2013-01-29T03:45:30.940 回答