-
Notifications
You must be signed in to change notification settings - Fork 4
/
Set Matrix Zeroes.txt
42 lines (38 loc) · 1.49 KB
/
Set Matrix Zeroes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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,应对其进行保留。
/////////////////
class Solution {
public:
void setFlag(vector<vector<int> > &matrix, int i, int j)
{
for(int p = 0; p < matrix[i].size(); p++)
if(matrix[i][p] != 0)
matrix[i][p] = -1;
for(int p = 0; p < matrix.size(); p++)
if(matrix[p][j] != 0)
matrix[p][j] = -1;
}
void setZeroes(vector<vector<int> > &matrix) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(matrix.empty())
return;
for(int i = 0; i < matrix.size(); i++)
for(int j = 0; j < matrix[0].size(); j++)
if(matrix[i][j] == 0)
{
matrix[i][j] = -1;
setFlag(matrix, i, j);
}
for(int i = 0; i < matrix.size(); i++)
for(int j = 0; j < matrix[0].size(); j++)
if(matrix[i][j] == -1)
matrix[i][j] = 0;
}
};