Set Matrix Zeroes

来源:互联网 发布:淘宝旧版本4.0.0下载 编辑:程序博客网 时间:2024/05/01 12:39

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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,则设置其所在的行和列的标记数组为true。(row[i] =true; column[j]= true)

然后第二遍遍历矩阵,如果row[i] 或者column[j]为true, 则设置matrix[i][j]=0;

void setZeroes(vector<vector<int> > &matrix){    int m=matrix.size();    int n=matrix[0].size();    bool *row = new bool[m];    memset(row,false,m);    bool *column = new bool[n];    memset(column,false,n);    for(int i=0;i<m;i++)    {        for(int j=0;j<n;j++)        {            if(matrix[i][j]==0)             {                 row[i]=true;                 column[j]=true;             }        }    }    for(int i=0;i<m;i++)    {        for(int j=0;j<n;j++)        {            if(row[i] || column[j])              matrix[i][j]=0;        }    }}


0 0
原创粉丝点击