【发布时间】:2014-01-01 20:21:45
【问题描述】:
这在技术上是一个代码挑战。 我在一次采访中被问到一个有趣的问题,我希望能得到一些见解,因为我能想出的最佳答案是 O(2n^2) - n 平方类别,但仍然是蛮力的。
假设您有一个 M × N 大小的矩阵(数组数组 (int[][]))
1 2 4 3 1
0 5 3 7 7
5 8 9 2 8
6 7 0 8 9
如果单元格包含零,则将整行和整列设置为零。
制作结果:
0 2 0 3 1
0 0 0 0 0
0 8 0 2 8
0 0 0 0 0
最快和/或最好的方法是什么?
我自己的答案是迭代整个数组数组,跟踪行和列以清零,然后将它们清零。
public void zeroOut(int[][] myArray){
ArrayList<Integer> rowsToZero = new....
ArrayList<Integer> columnsToZero = new....
for(int i=0; i<myArray.length; i++){ // record which rows and columns will be zeroed
for(int j=0; j<myArray[i].length; i++){
if(myArray[i][j] == 0){
if(!rowsToZero.contains(i)) rowsToZero.add(i);
if(!columnsToZero.contains(j)) columnsToZero.add(j);
}
}
}
for(int row : rows){ // now zero the rows
myArray[row] = int[myArray.length];
}
for(int i=0; i<myArray.length; i++){
for(int column: columns){ // now zero the columns
myArray[i][column] = 0;
}
}
}
有没有更好的算法?有没有更好的数据结构来表示这个矩阵?
【问题讨论】:
-
你有 O(N^2) 的数据要处理,所以显然它不能比 O(N^2) 更快地完成。坚持你所拥有的。
-
你必须访问每个单元格以检查是否存在 0,所以你不能做得比 O(m*n) 更好......你的方法对我来说似乎很直观
-
如何从每一行和每一列制作一个 HashMap(你最终得到 M + N HashMap(s)),然后对他们每个人询问:
if (hmap.contains(0)){/*zero out the column or row it represents*/} -
@RichardPlunkett M x N 矩阵(大写 N)。 M*N=n 要处理的数据数。 OP说
O(2n^2),你说O(N^2) -
您应该使用
HashSet而不是ArrayList,因为contains方法的成本为O(1) 而不是O(n)。为了将行归零,您可以使用固定数组来降低内存成本。
标签: java arrays algorithm matrix time-complexity