[LeetCode] 73. Set Matrix Zeroes

来源:互联网 发布:lca算法建模 编辑:程序博客网 时间:2024/06/07 06:53

[LeetCode] 73. Set Matrix Zeroes


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?


题意是把数组中为0的位置对应的行和列都设为0。

思路: 想了很久都没想到O(1)空间复杂度,太蠢了,就先用O(m+n)的空间复杂度硬爆先吧。
用两个数组分别记录为0的行和列的下标,然后最后遍历的时候设0。


class Solution {public:    void setZeroes(vector<vector<int>>& matrix) {        int leni = matrix.size();        if (leni == 0) {            return;        }        vector<int> is0i;        vector<int> is0j;        int lenj = matrix[0].size();        for (int i=0; i<leni; ++i) {            for (int j=0; j<lenj; ++j) {                if (matrix[i][j] == 0) {                    is0i.push_back(i);                    is0j.push_back(j);                }            }        }        for (int i=0; i<is0i.size(); ++i) {            for (int j=0; j<lenj; ++j) {                matrix[is0i[i]][j] = 0;            }        }        for (int j=0; j<is0j.size(); ++j) {            for (int i=0; i<leni; ++i) {                matrix[i][is0j[j]] = 0;            }        }    }};

然后去Discuss学习了一波,人家把记录这些信息的都放在matrix的第一行和第一列,然后用两个boolean值来特别处理第一行和第一列即可。

0 0
原创粉丝点击