Set Matrix Zeroes

来源:互联网 发布:存货管理毕业论文数据 编辑:程序博客网 时间:2024/04/29 19:02

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?



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();        if (m<=0)            return;                    int n = matrix[0].size();        if (n<=0)            return;                    bool row=false;        bool col=false;                for(int i=0; i< n; i++){            if (matrix[0][i] == 0){                row = true;                break;            }        }        for(int i=0; i< m; i++){            if (matrix[i][0] == 0){                col = true;                break;            }        }                for(int i = 0; i < n;  i++)            for(int j = 0; j<m; j++){                if (matrix[j][i] == 0){                    matrix[j][0] = 0;                    matrix[0][i] =0;                }            }                    for(int i =1; i < n;  i++)            for(int j = 1; j<m; j++){            if (matrix[j][0] == 0 || matrix[0][i] == 0)                matrix[j][i]=0;            }                    if (row == true){            for (int i = 0; i < n; i++)                matrix[0][i] = 0;        }                if (col == true){            for (int i = 0; i < m; i++)                matrix[i][0] = 0;        }            }};


不得不再提醒自己,不要想着一次性得到最优解,先写一个简单的,思路清晰,bugfree最重要!!

1. 对于 O(m + n) 可以用vector,减少时间 O(nm)前面的系数

2. 对于 constant space,就牺牲点时间复杂度好了。 同first missing positive number,利用数据本身做存储,以达到constant memory的目的

最开始的时候想把两个都点都集中起来,天呢,麻烦死了……又是swap,又是判断的……

3. 

for(int i =1; i < n;  i++)            for(int j = 1; j<m; j++){            if (matrix[j][0] == 0 || matrix[0][i] == 0)                matrix[j][i]=0;            }
最开始这里面的1都用0代替,明显不该用的信息别我用了,导致出现全0




原创粉丝点击