本文共 2390 字,大约阅读时间需要 7 分钟。
class Solution {//let the first row and first col to keep the record//if matrix[row][col] == 0 && col == 0, then firstColZero = true, same to firstRowZeropublic: void setZeroes(vector> &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int rowNum = matrix.size(); if(0 == rowNum) return; int colNum = matrix[0].size(); bool firstRowZero, firstColumnZero; firstRowZero = firstColumnZero = false; for (int row = 0; row < rowNum; ++row) { for (int col = 0; col < colNum; ++col) { if (!matrix[row][col]) { if(row == 0) firstRowZero = true; if(col == 0) firstColumnZero = true; matrix[row][0] = 0; matrix[0][col] = 0; } } } //according the flag in first row and first col to set the row and col to zero corresponding for(int row = 1; row < rowNum; ++row) { if(0 == matrix[row][0]) { for (int col = 0; col < colNum; ++col) matrix[row][col] = 0; } } // for(int col = 1; col < colNum; ++col) { if(0 == matrix[0][col]) { for (int row = 0; row < rowNum; ++row) matrix[row][col] = 0; } } // if(firstRowZero) for (int col = 0; col < colNum; ++col) matrix[0][col] = 0; if(firstColumnZero) for (int row = 0; row < rowNum; ++row) matrix[row][0] = 0; }};
second time
class Solution {public: void setZeroes(vector> &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = matrix.size(); if(n == 0) return; int m = matrix[0].size(); if(m == 0) return; bool firstRow = false; bool firstColumn = false; for(int i = 0; i < n; ++i) { if(matrix[i][0] == 0) { firstColumn = true; break; } } for(int j = 0; j < m; ++j) { if(matrix[0][j] == 0) { firstRow = true; break; } } //using first row and first column to keep record for(int i = 1; i < n; ++i) { for(int j = 1; j < m; ++j) { if(matrix[i][j] == 0) matrix[0][j] = 0, matrix[i][0] = 0; } } //set zero for(int i = 1; i < n; ++i) { if(matrix[i][0] == 0) { for(int j = 1; j < m; ++j) matrix[i][j] = 0; } } for(int j = 1; j < m; ++j) { if(matrix[0][j] == 0) { for(int i = 1; i < n; ++i) matrix[i][j] = 0; } } //set first row and first colum if(firstRow) { for(int j = 0; j < m; ++j) matrix[0][j] = 0; } if(firstColumn) { for(int i = 0; i < n; ++i) matrix[i][0] = 0; } }};
转载地址:http://tqxti.baihongyu.com/