码迷,mamicode.com
首页 > 其他好文 > 详细

Set Matrix Zeroes -- leetcode

时间:2015-04-12 10:40:06      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:leetcode   面试   matrix   矩阵   清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?


算法思路:

1. 借用第一行和一列作为标志,进行两趟扫描。

2. 第一趟扫描,标志出该行该列是为需要清0.

3. 第二趟扫描,利用标志进行对具体位清0操作。

4. 由于第一行,第一列被复用来作标志, 他们本身需要额外的变量,来指示,是否第一行,第一列需要清0.

5. 由于第一行,是否清0,可以用第一行中第一列的位来表示。 故可以省去一位标专。 只需要一个标志,来指示第一列是否清0.

注,第二趟,是从底到顶,以保证第一行标志位,在结束标志用处后,才处理第一行。


class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        if (matrix.empty() || matrix[0].empty()) return;
        
        bool col0 = false;
        for (int i=0; i<matrix.size(); i++) {
            if (!matrix[i][0]) col0 = true;
            for (int j=1; j<matrix[i].size(); j++) {
                if (!matrix[i][j])
                    matrix[i][0] = matrix[0][j] = 0;
            } 
        }
        
        for (int i=matrix.size()-1; i>=0; i--) {
            for (int j=1; j<matrix[i].size(); j++) {
                if (!matrix[i][0] || !matrix[0][j])
                    matrix[i][j] = 0;
            }
            if (col0) matrix[i][0] = 0;
        }
        
    }
};


算法参考自

https://leetcode.com/discuss/15997/any-shortest-o-1-space-solution

Set Matrix Zeroes -- leetcode

标签:leetcode   面试   matrix   矩阵   清0   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45007885

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!