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

leetcode------Set Matrix Zeroes

时间:2015-02-09 12:43:33      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

标题: Set Matrix Zeroes
通过率: 31.3%
难度: 中等

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?

本题的特点就是怎么用最少的额外空间去处理本题,最弱的也就是用另外一个mn的数组,或者就是用两个一维数组去记录行列,
那么我想到的是不用任何额外的空间,方法如下:
用数组的第0行和第0列去记录需要置0的行列,也就是说,如果matrix[i][j]=0那么需要把matrix[i][0]=0,matrix[0][j]=0的操作,这样一个
m*n循环下来以后就把需要置0的行列进行的标记,!!!
注意,在上一步之前先要确定第一行和第一列原来是否就有0的存在,这一部非常重要,如果不记录的话直接从上一步走,那么最好的结果是整个矩阵都是0,
接着是置0操作,是从第一行第一列开始的!这一步也是非常关键,
最后,要做的就是对第0行第0列进行操作,前面已经记录过是否有0,
下面直接看代码:
 1 public class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         int m=matrix.length;
 4         int n=matrix[0].length;
 5         boolean falg=false,mb=false,nb=false;
 6        
 7         for(int i=0;i<m;i++){
 8             if(matrix[i][0]==0){
 9                 mb=true;
10             }
11         }
12         for(int i=0;i<n;i++){
13             if(matrix[0][i]==0){
14                 nb=true;
15             }
16         }
17         for(int i=0;i<m;i++){
18             for(int j=0;j<n;j++){
19                 if(matrix[i][j]==0){
20                     matrix[i][0]=0;
21                     matrix[0][j]=0;
22                 }
23             }
24         }
25         for(int i=1;i<m;i++){
26             for(int j=1;j<n;j++){
27                 if(matrix[i][0]==0||matrix[0][j]==0){
28                     matrix[i][j]=0;
29                 }
30             }
31         }
32         if(mb){
33              for(int i=0;i<m;i++){
34              matrix[i][0]=0;
35             }
36         }
37         if(nb){
38              for(int i=0;i<n;i++){
39              matrix[0][i]=0;
40             }
41         }
42     }
43 
44         
45     
46 }

 

leetcode------Set Matrix Zeroes

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4281072.html

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