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

Set Matrix Zeroes

时间:2015-05-14 23:19:26      阅读:148      评论: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
运行时间:87ms
 
 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int>>& matrix) {
 4         int row = matrix.size();
 5         int col = matrix[0].size();
 6         
 7         vector<int> vRow(row, 0);
 8         vector<int> vCol(col, 0);
 9         for(int i = 0; i < row; i++){
10             for(int j = 0; j < col; j++){
11                 if(matrix[i][j] == 0){
12                     vRow[i] = 1;
13                     vCol[j] = 1;
14                 }
15             }
16         }
17         for(int i = 0; i < row; i++){
18             if(vRow[i] == 1){
19                 for(int j = 0; j < col; j++) matrix[i][j] = 0;
20             }
21         }
22         for(int j = 0; j < col; j++){
23             if(vCol[j] == 1){
24                 for(int i = 0; i < row; i++) matrix[i][j] = 0;
25             }
26         }
27         return;
28     }
29 };

 

Set Matrix Zeroes

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4504672.html

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