[leetcode] Set Matrix Zeroes

来源:互联网 发布:淘宝达人如何吸粉 编辑:程序博客网 时间:2024/04/29 22:22

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

代码:

class Solution {public:    void setZeroes(vector<vector<int> > &matrix) {        int m=matrix.size(),n=matrix[0].size();        int row[m],col[n];        memset(row,1,sizeof(row));        memset(col,1,sizeof(col));        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                if(matrix[i][j]==0){                    row[i]=0;                    col[j]=0;                }            }        }        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                if(row[i]==0 || col[j]==0){                    matrix[i][j]=0;                }            }        }        return;    }};


0 0
原创粉丝点击