Set Matrix Zeroes (LeetCode)
Question:
https://oj.leetcode.com/problems/set-matrix-zeroes/
解答:
可以用external space的话,可以用两个array, A[N] and B[M]. 当matrix[i][j] == 0,就把A[i]和B[j]设成0,最后matrix[i][j] = 0 if A[i]==0 || B[j] == 0
如果不能用外部空间,可以用第一行和第一列来做类似的工作。只是需要事先记录下第一行和第一列本身有没有0.
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { int row = matrix.size(); if (row == 0) return; int col = matrix[0].size(); if (col == 0) return; // handle the first row/col bool firstRow = false; bool firstCol = false; for (int i = 0; i < row; i++) { if (matrix[i][0] == 0) { firstCol = true; break; } } for (int i = 0; i < col; i++) { if (matrix[0][i] == 0) { firstRow = true; break; } } for (int i = 1; i < row; i++) { for (int j = 1; j < col; j++) { if (matrix[i][j] == 0) { matrix[0][j] = 0; matrix[i][0] = 0; } } } for (int i = 1; i < row; i++) { for (int j = 1; j < col; j++) { if (matrix[0][j] == 0 || matrix[i][0] == 0) matrix[i][j] = 0; } } if (firstCol) { for (int i = 0; i < row; i++) matrix[i][0] = 0; } if (firstRow) { for (int i = 0; i < col; i++) matrix[0][i] = 0; } } };
浙公网安备 33010602011771号