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

[leetcode] Set Matrix Zeroes

时间:2014-07-07 23:02:31      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

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?

https://oj.leetcode.com/problems/set-matrix-zeroes/

 

最佳思路:就是先遍历二维数组,然后用首行和首列作为标记是否整行整列要设为0。对于首行首列本身,另用两个boolean记录。

 

bubuko.com,布布扣
public class Solution {
    public void setZeroes(int[][] matrix) {
        if(matrix==null||matrix.length==0||matrix[0].length==0)
            return;
        int m=matrix.length;
        int n=matrix[0].length;
        
        int i,j;
        boolean isFirstRowZero=false;
        boolean isFirstColZero=false;
        for(i=0;i<m;i++){
            if(matrix[i][0]==0){
                isFirstColZero=true;
                break;
            }
        }
        for(i=0;i<n;i++){
            if(matrix[0][i]==0){
                isFirstRowZero=true;
                break;
            }
            
        }
        
        for(i=0;i<m;i++){
            for(j=0;j<n;j++){
                if(matrix[i][j]==0){
                    matrix[0][j]=0;
                    matrix[i][0]=0;
                }
                
            }
            
        }
        
        for(i=1;i<m;i++){
            if(matrix[i][0]==0){
                for(j=0;j<n;j++)
                    matrix[i][j]=0;
            }
            
        }
        
        for(i=1;i<n;i++){
            if(matrix[0][i]==0){
                for(j=0;j<m;j++)
                    matrix[j][i]=0;
            }
        }
        
        if(isFirstRowZero){
            for(i=0;i<n;i++)
                matrix[0][i]=0;
        }
        
        if(isFirstColZero){
            for(i=0;i<m;i++)
                matrix[i][0]=0;
        }
        
        return;
        
    }
}
View Code

 

参考:

http://jane4532.blogspot.com/2013/09/set-matrix-zeroleetcode.html

[leetcode] Set Matrix Zeroes,布布扣,bubuko.com

[leetcode] Set Matrix Zeroes

标签:style   blog   http   color   strong   os   

原文地址:http://www.cnblogs.com/jdflyfly/p/3812809.html

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