【问题标题】:Big O notation O(NM) or (N^2)大 O 表示法 O(NM) 或 (N^2)
【发布时间】:2013-01-29 03:42:10
【问题描述】:

有人告诉我下面的代码是 = 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; 
           }
      } 
  }
}

【问题讨论】:

    标签: java loops for-loop big-o


    【解决方案1】:

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

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

    【讨论】:

    • 您的假设是正确的 M 和 N 分别指的是行和列。感谢您及时的回复。这是有道理的!
    • 但是,如果 M 总是
    • 如果 M
    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2022-01-13
    相关资源
    最近更新 更多