题目描述:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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?
解题思路:
这题题目的要求是不要使用额外的空间,所以我们这题可以用第一行和第一列作为是否要将那一行、那一列清零的标志:题目要求当我们碰到一个元素matrix[i][j]为零时将元素所在的那一行和那一列清零,如上,我们将matrix[i][0]和matrix[0][j]清零,到最后我们只要把第一列中的为0元素的那一列清零即可,第一行同理。但这样无法处理第一行和第一列本身就有0的情况,所以我们要先判断第一行和第一列本身是否有零。
当然,你如果不想用第一行第一列也可以用最后一行最后一列,思路还是一样的。
代码:
1 class Solution { 2 public: 3 void setZeroes(vector<vector<int>>& matrix) { 4 int row = matrix.size(); 5 int col = matrix[0].size(); 6 bool isZero_Fcol = false, isZero_Frow = false; 7 for(int i = 0; i < col; i++) 8 if(matrix[0][i] == 0){ 9 isZero_Fcol = true; 10 break; 11 } 12 for(int i = 0; i < row; i++) 13 if(matrix[i][0] == 0){ 14 isZero_Frow = true; 15 break; 16 } 17 for(int i = 1; i < row; i++){ 18 for(int j = 1; j < col; j++){ 19 if(matrix[i][j] == 0){ 20 matrix[0][j] = 0; 21 matrix[i][0] = 0; 22 } 23 } 24 } 25 for(int i = 1; i < row; i++){ 26 for(int j = 1; j < col; j++){ 27 if(matrix[i][0] == 0 || matrix[0][j] == 0) 28 matrix[i][j] = 0; 29 } 30 } 31 if(isZero_Fcol){ 32 for(int i = 0; i < col; i++) 33 matrix[0][i] = 0; 34 } 35 if(isZero_Frow){ 36 for(int i = 0; i < row; i++){ 37 matrix[i][0] = 0; 38 } 39 } 40 } 41 };