set-matrix-zeroes

来源:互联网 发布:win10有网络不能上网 编辑:程序博客网 时间:2024/03/29 19:06

给定一个m×n矩阵,如果一个元素是0,则将其所在行和列全部元素变成0。

需要在原地完成。

您在真实的面试中是否遇到过这个题? 
Yes
样例

给出一个矩阵[[1,2],[0,3]],返回[[0,2],[0,0]]

不使用额外空间
class Solution {public:    /**     * @param matrix: A list of lists of integers     * @return: Void     */    void setZeroes(vector<vector<int> > &matrix) {        // write your code here        int row=matrix.size();        if(row==0) return;        int col=matrix[0].size();        if(col==0) return;        bool firstcolhaszero=false;        for(int i=0;i<row;i++){            if(matrix[i][0]==0) firstcolhaszero=true;          }        bool firstrowhaszero=false;;        for(int i=0;i<col;i++){            if(matrix[0][i]==0) firstrowhaszero=true;        }        for(int i=1;i<row;i++){            for(int j=1;j<col;j++){                if(matrix[i][j]==0){                    matrix[i][0]=0;                    matrix[0][j]=0;                }            }        }        for(int i=1;i<row;i++){            if(matrix[i][0]==0){                for(int j=1;j<col;j++) matrix[i][j]=0;            }        }        for(int i=1;i<col;i++){            if(matrix[0][i]==0){                for(int j=1;j<row;j++) matrix[j][i]=0;            }        }        if(firstcolhaszero){            for(int i=0;i<row;i++){                matrix[i][0]=0;            }        }        if(firstrowhaszero){            for(int i=0;i<col;i++){                matrix[0][i]=0;            }        }    }};


0 0
原创粉丝点击