首页 > 其他 > 详细

Set Matrix Zeroes

时间:2014-03-13 07:48:43      阅读:499      评论: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.

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个数个空间,不是常数。
在0排和0列记录哪排哪列需要置零。这两行需要在修改之前判断是否需要置零,只需2个额外空间。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        int flag1 = 0;
        int flag0 = 0;
         
        for(int i = 0 ; i < matrix.size();i++)
        if(matrix[i][0] == 0)flag1 = 1;
         
        for(int i = 0 ; i < matrix[0].size();i++)
        if(matrix[0][i] == 0)flag0 = 1;
         
        for(int i = 1 ; i < matrix.size();i++)
        for(int j = 1 ; j < matrix[0].size();j++)
        {
            if(matrix[i][j] == 0)
            {
                matrix[0][j] = 0;
                matrix[i][0] = 0;
            }
        }
         
        for(int i = 1 ; i < matrix.size();i++)
        {
            if(matrix[i][0] == 0)
            for(int j = 1 ; j < matrix[i].size();j++)matrix[i][j]=0;
        }
        for(int i = 1 ; i < matrix[0].size();i++)
        {
            if(matrix[0][i] == 0)
            for(int j = 1 ; j < matrix.size();j++)matrix[j][i]=0;
        }
        if(flag1 == 1)for(int i = 0 ; i < matrix.size();i++)matrix[i][0] = 0;
        if(flag0 == 1)for(int i = 0 ; i < matrix[0].size();i++)matrix[0][i] = 0;
         
    }
};

  

Set Matrix Zeroes,布布扣,bubuko.com

Set Matrix Zeroes

原文:http://www.cnblogs.com/pengyu2003/p/3596314.html

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