程序员人生 网站导航

Leetcode 73 Set Matrix Zeroes

栏目:php教程时间:2016-09-28 09:19:12

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; } }



------分隔线----------------------------
------分隔线----------------------------

最新技术推荐