Leetcode 73 Set Matrix Zeroes

2018-01-12 15:00:41 浏览数 (1)

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点,并将所在行列都置0

具体要求为使用较小的空间,开始m n的做法

代码语言:javascript复制
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        vector<int> x;
        for(int i=0;i<matrix.size();i  )
            for(int j=0;j<matrix[0].size();j  )
                if(matrix[i][j]==0)
                {
                    x.push_back(i);
                    x.push_back(j);
                }
        for(int i=0;i<x.size();i =2)
        {
            for(int j=0;j<matrix.size();j  ) matrix[j][x[i 1]]=0;
            for(int j=0;j<matrix[0].size();j  ) matrix[x[i]][j]=0;
        }
    }
};

在discuss中看到的O(1)做法,将是否有0存在每一行每一列的第一个位置,

因为行列会交叉,因而会当左上角为0时会不知道到底是行还是列,

所以引入col0记录,col0为0表示是第一列产生的0

代码语言:javascript复制
void setZeroes(vector<vector<int> > &matrix) {
    int col0 = 1, rows = matrix.size(), cols = matrix[0].size();

    for (int i = 0; i < rows; i  ) {
        if (matrix[i][0] == 0) col0 = 0;
        for (int j = 1; j < cols; j  )
            if (matrix[i][j] == 0)
                matrix[i][0] = matrix[0][j] = 0;
    }

    for (int i = rows - 1; i >= 0; i--) {
        for (int j = cols - 1; j >= 1; j--)
            if (matrix[i][0] == 0 || matrix[0][j] == 0)
                matrix[i][j] = 0;
        if (col0 == 0) matrix[i][0] = 0;
    }
}

0 人点赞