首页 > 其他 > 详细

Set Matrix Zeroes

时间:2015-06-16 18:46:34      阅读:175      评论:0      收藏:0      [点我收藏+]

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,O(mn),即用的一个相同大小的矩阵来记录那个位置有0.

2,O(m + n),就是加一行一列来标记哪行哪列有0。

3,常数空间,即考虑不使用额外的空间,可以把第一行与第一列作为标记行与标记列,但是得先确定第一行与第一列本身要不要设为0。

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
       if (matrix.size() < 1) return;
         int row = matrix.size(), col = matrix[0].size();
         bool r0 = false, c0 = false;
         for (int i = 0; i < row; ++i) {
             if (matrix[i][0] == 0) {
                 c0 = true; break;
             }
         }
         for (int j = 0; j < col; ++j) {
             if (matrix[0][j] == 0) {
                 r0 = true; break;
             }
         }
         for (int i = 1; i < row; ++i) {
             for (int j = 1; j < col; ++j) {
                 matrix[i][0] = (matrix[i][j] == 0) ? 0 : matrix[i][0];
                 matrix[0][j] = (matrix[i][j] == 0) ? 0 : matrix[0][j];
             }   
         }
         for (int i = 1; i < row; ++i) {
             for (int j = 1; j < col; ++j) {
                  matrix[i][j] = (matrix[i][0] == 0) ? 0 : matrix[i][j];
                  matrix[i][j] = (matrix[0][j] == 0) ? 0 : matrix[i][j];
            }   
         }
         for (int i = 0; i < row && c0; ++i)  matrix[i][0] = 0;
         for (int j = 0; j < col && r0; ++j)  matrix[0][j] = 0; 
    }
};

 

Set Matrix Zeroes

原文:http://www.cnblogs.com/qiaozhoulin/p/4581259.html

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