问题描述:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ]
Example 2:
Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ]
Follow up:
- 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?
解题思路:
新建两个vector来分别存储出现0的行和列。
首先遍历矩阵,将出现值为零的行和列分别加入数组
遍历两个数组,将值设为0;
时间复杂的: O(m*n) 空间复杂度:O(n+m)
代码:
我的解法O(m+n):
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) return; int m = matrix.size(); int n = matrix[0].size(); vector<int> row; vector<int> col; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(matrix[i][j] == 0){ row.push_back(i); col.push_back(j); } } } for(int r : row){ for(int i = 0; i < n; i++) matrix[r][i] = 0; } for(int c : col){ for(int i = 0; i < m; i++) matrix[i][c] = 0; } } };
来看看空间复杂度为O(1)的解法:来自lugiavn的解法
O(1)
首先找到含有0的最后一行,并用它来存储出现0的列的位置。
遍历行,将含有0的行设置为0,并将列的位置存储到最后一行出现0的行中
遍历最后一行并设置行。
很聪明的解法了!
因为这一行也要被设置为0,所以可以用它来暂时存储列的位置!
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { int H = matrix.size(); int W = matrix[0].size(); // find the last 0 row int last_0_row = -1; for (int y = H - 1; y >= 0 && last_0_row == -1; y--) for (int x = 0; x < W; x++) if (matrix[y][x] == 0) { last_0_row = y; break; } if (last_0_row == -1) return; // go row by row for (int y = 0; y < last_0_row; y++) { bool this_is_a_0_row = false; for (int x = 0; x < W; x++) { if (matrix[y][x] == 0) { this_is_a_0_row = true; matrix[last_0_row][x] = 0; } } if (this_is_a_0_row) for (int x = 0; x < W; x++) { matrix[y][x] = 0; } } // set collums to 0 for (int y = 0; y < H; y++) for (int x = 0; x < W; x++) { if (matrix[last_0_row][x] == 0) matrix[y][x] = 0; } // set the last 0 row for (int x = 0; x < W; x++) { matrix[last_0_row][x] = 0; } } };