首页 > 其他 > 详细

【LeetCode从零单刷】Set Matrix Zeroes

时间:2015-11-01 10:13:15      阅读:253      评论:0      收藏:0      [点我收藏+]

题目:

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,就可以了。
但是这样有一个弊端:修改原矩阵元素,又基于原矩阵判断,但判断全部基于原值,需要新变量记录原值。因此需要第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;
    }
};

版权声明:本文为博主原创文章,转载请联系我的新浪微博 @iamironyoung

【LeetCode从零单刷】Set Matrix Zeroes

原文:http://blog.csdn.net/ironyoung/article/details/49556051

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!