題目
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
Follow up:Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
題目要求使用常數的額外空間,因此需要借助矩陣本身的空間來輔助存儲,這裡借用了矩陣的第一行和第一列來輔助紀錄該行或該列是否為0.由於第一行第一列自身發生了改變,再用兩個布爾變量紀錄第一行和第一列是否為0即可。
代碼
public class SetMatrixZeroes { public void setZeroes(int[][] matrix) { if (matrix == null || matrix.length == 0) { return; } int M = matrix.length; int N = matrix[0].length; boolean isFirstRowZero = false; boolean isFirstColumnZero = false; for (int j = 0; j < N; ++j) { if (matrix[0][j] == 0) { isFirstRowZero = true; break; } } for (int i = 0; i < M; ++i) { if (matrix[i][0] == 0) { isFirstColumnZero = true; break; } } for (int i = 1; i < M; ++i) { for (int j = 1; j < N; ++j) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = 1; i < M; ++i) { for (int j = 1; j < N; ++j) { if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; } } if (isFirstRowZero) { for (int j = 0; j < N; ++j) { matrix[0][j] = 0; } } if (isFirstColumnZero) { for (int i = 0; i < M; ++i) { matrix[i][0] = 0; } } } }