Leetcode 73 Set Matrix Zeroes
來源:程序員人生 發布時間:2016-09-28 09:19:12 閱讀次數:2520次
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
具體要求為使用較小的空間,開始m+n的做法
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
vector<int> x;
for(int i=0;i<matrix.size();i++)
for(int j=0;j<matrix[0].size();j++)
if(matrix[i][j]==0)
{
x.push_back(i);
x.push_back(j);
}
for(int i=0;i<x.size();i+=2)
{
for(int j=0;j<matrix.size();j++) matrix[j][x[i+1]]=0;
for(int j=0;j<matrix[0].size();j++) matrix[x[i]][j]=0;
}
}
};
在discuss中看到的O(1)做法,將是不是有0存在每行每列的第1個位置,
由于行列會交叉,因此會當左上角為0時會不知道究竟是行還是列,
所以引入col0記錄,col0為0表示是第1列產生的0
void setZeroes(vector<vector<int> > &matrix) {
int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) col0 = 0;
for (int j = 1; j < cols; j++)
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (col0 == 0) matrix[i][0] = 0;
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈