[leetcode] Set Matrix Zeroes

来源:互联网 发布:linux在线音乐软件 编辑:程序博客网 时间:2024/05/18 09:23

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?

按照题目中的意思,o(mn)的算法很挫,所以,记录下0元素的坐标的做法肯定是最差的了:方法如下

class Solution {public:    void setZeroes(vector<vector<int> > &matrix) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int m=matrix.size();        int n=matrix[0].size();        int (*p)[2]=new int[m*n][2];        int count=0;        for(int i=0 ; i<m ; i++){    for(int j=0 ; j<n ; j++)if(matrix[i][j]==0){p[count][0]=i;p[count][1]=j;count++;}}for(int k=0 ; k<count ; k++){for(int i=0 ; i<m ; i++)matrix[i][p[k][1]]=0;for(int j=0 ; j<n ; j++)matrix[p[k][0]][j]=0;}    }};

A simple improvement uses O(m + n) space, but still not the best solution.当然一个简单的改进就是记录下所有要变成0的行和列就行了

class Solution {public:    void setZeroes(vector<vector<int> > &matrix) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int m=matrix.size();        int n=matrix[0].size();        bool *p=new bool[m]();    bool *q=new bool[n]();        for(int i=0 ; i<m ; i++){for(int j=0 ; j<n ; j++)if(matrix[i][j]==0){p[i]=true;q[j]=true;}}for(int i=0 ; i<m ; i++){if(p[i])for(int j=0 ; j<n ; j++)matrix[i][j]=0;}for(int j=0 ; j<n ; j++){if(q[j])for(int i=0 ; i<m ; i++)matrix[i][j]=0;}    }};

下面这个是只用了常数的额外空间。

class Solution {public:    void setZeroes(vector<vector<int> > &matrix) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int m=matrix.size();        int n=matrix[0].size();        bool zerorow,zerocol;        zerorow=zerocol=false;        for(int i=0 ; i<m ; i++){    if(matrix[i][0]==0){zerocol=true;break;}}for(int j=0 ; j<n ; j++){if(matrix[0][j]==0){zerorow=true;break;}}for(int i=1 ; i<m ; i++){for(int j=1 ; j<n ; j++){if(matrix[i][j]==0){matrix[0][j]=0;matrix[i][0]=0;}}}for(int i=1 ; i<m ; i++){if(matrix[i][0]==0){for(int j=0 ; j<n ; j++)matrix[i][j]=0;}}for(int j=1 ; j<n ; j++){if(matrix[0][j]==0){for(int i=0 ; i<m ; i++)matrix[i][j]=0;}}if(zerocol)for(int i=0 ; i<m ; i++)matrix[i][0]=0;if(zerorow)for(int j=0 ; j<n ; j++)matrix[0][j]=0;    }};


原创粉丝点击