首页 > 其他 > 详细

Set Matrix Zeroes

时间:2014-04-08 06:13:59      阅读:510      评论: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?

Solution: Use first row and column as auxiliary spaces instead of newly allocating ones.

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int> > &matrix) {
 4         if(matrix.empty()) return;
 5         int R = matrix.size();
 6         int C = matrix[0].size();
 7         bool firstRowZero = false;
 8         bool firstColZero = false;
 9         
10         for(int j = 0; j < C; j++) {
11             if(matrix[0][j] == 0) {
12                 firstRowZero = true;
13                 break;
14             }
15         }
16         
17         for(int i = 0; i < R; i++) {
18             if(matrix[i][0] == 0) {
19                 firstColZero = true;
20                 break;
21             }
22         }
23         
24         for(int i = 1; i < R; i++) {
25             for(int j = 1; j < C; j++) {
26                 if(matrix[i][j] == 0) {
27                     matrix[i][0] = 0;
28                     matrix[0][j] = 0;
29                 }
30             }
31         }
32         
33         for(int i = 1; i < R; i++)
34             if(matrix[i][0] == 0)
35                 for(int j = 1; j < C; j++)
36                     matrix[i][j] = 0;
37         
38         for(int j = 1; j < C; j++)
39             if(matrix[0][j] == 0)
40                 for(int i = 1; i < R; i++)
41                     matrix[i][j] = 0;
42                     
43         if(firstRowZero)
44             for(int j = 0; j < C; j++)
45                 matrix[0][j] = 0;
46                 
47         if(firstColZero)
48             for(int i = 0; i < R; i++)
49                 matrix[i][0] = 0;
50     }
51 };
bubuko.com,布布扣

 

Set Matrix Zeroes,布布扣,bubuko.com

Set Matrix Zeroes

原文:http://www.cnblogs.com/zhengjiankang/p/3651166.html

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