[LeetCode] 73. Set Matrix Zeroes

来源:互联网 发布:品牌女装淘宝店铺 编辑:程序博客网 时间:2024/06/05 20:25

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?

// O(m * n)空间复杂度, 56msclass Solution {public:    void setZeroes(vector<vector<int>>& matrix) {        vector<vector<int>> copied(matrix);        const int m = matrix.size(), n = matrix[0].size();        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (copied[i][j] == 0) {                    for (int ii = 0; ii < m; ii++)                        matrix[ii][j] = 0;                    for (int jj = 0; jj < n; jj++)                        matrix[i][jj] = 0;                }            }        }    }};
// O(m + n)空间复杂度, 53msclass Solution {public:    void setZeroes(vector<vector<int>>& matrix) {        const int m = matrix.size(), n = matrix[0].size();        vector<int> rowtrack, coltrack;        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (matrix[i][j] == 0) {                    rowtrack.push_back(i);                    coltrack.push_back(j);                }            }        }        for (auto row : rowtrack) {            for (int jj = 0; jj < n; jj++)                matrix[row][jj] = 0;        }        for (auto col : coltrack) {            for (int ii = 0; ii < m; ii++)                matrix[ii][col] = 0;        }    }};
// O(1)空间复杂度,class Solution {public:    void setZeroes(vector<vector<int>>& matrix) {        const int m = matrix.size(), n = (int)matrix[0].size();        int BaseRow = -1;        bool WipeThisRow = false;        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (matrix[i][j] == 0) {                    if (BaseRow < 0) {                        BaseRow = i;                        break;                    }                    WipeThisRow = true;                    if (i != BaseRow)                        swap(matrix[BaseRow][j], matrix[i][j]);                }            }            if (WipeThisRow && i != BaseRow) {                for (int jj = 0; jj < n; jj++)                    matrix[i][jj] = 0;                WipeThisRow = false;            }        }        if (BaseRow >= 0) {            for (int j = 0; j < n; j++) {                if (matrix[BaseRow][j] == 0) {                    for (int ii = 0; ii < m; ii++)                        matrix[ii][j] = 0;                }                matrix[BaseRow][j] = 0;            }        }    }};

这里写图片描述这里写图片描述

原创粉丝点击