【LeetCode从零单刷】Set Matrix Zeroes

来源:互联网 发布:淘宝阿里旺旺在哪里 编辑:程序博客网 时间:2024/05/22 00:31

题目:

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 元素。

  1. O(mn)空间复杂度的方法很简单,设置一个 False 初值组成的新矩阵,遍历全矩阵的元素,发现 0 则行、列全置 true
  2. O(m+n)空间复杂度需要想一想,如果是为了行、列全 0,是不是只要保存单独行、列的信息就好了?只要多增加一行、一列记录 bool 值就好了
  3. O(1)空间复杂度呢?基本有两种思路:(1)开辟常数新空间;(2)利用已有空间
如果利用第二种方法,将它用在O(1)空间复杂度,用原矩阵的第1行和第1列的值记录此行是否为0,就可以了。
但是这样有一个弊端:修改原矩阵元素,但判断全部基于原值,需要新变量记录原值
in-place 问题有种常见的方法:利用中间编码,同时保存上一个状态和当前状态的信息,最后解码。具体见《Game Of Life》。
因此需要第1行和第1列是否是否置为0,需要另外的2个 bool 值来记录。基本思路是:
  1. 2个bool值第1行、第1列是否全0,此时不修改值;【2个新开辟元素=》第1行、第1列】
  2. 第1行、第1列记录第2~n行 、 第2~m列是否全0。然后根据记录修改第2~n行 、 第2~m列元素;【第1行、第1列=》第2~n行 、 第2~m列】
  3. 根据第1步中bool值,修改特殊的第1行、第1列元素是否全0
class Solution {public:    void setZeroes(vector<vector<int>>& matrix) {        int row = matrix.size();        int col = matrix[0].size();        if(row <= 1 && col <= 1)    return;                bool zerorow = false;        bool zerocol = false;        for(int i = 0; i < row; i++)        {            if(matrix[i][0] == 0)            {                zerocol = true;                break;            }        }                for(int i = 0; i < col; i++)        {            if(matrix[0][i] == 0)            {                zerorow = true;                break;            }        }                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(zerorow)        {            for(int i = 0; i< col; i++) matrix[0][i] = 0;        }                if(zerocol)        {            for(int i = 0; i< row; i++) matrix[i][0] = 0;        }                return;    }};

0 0
原创粉丝点击