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

将矩阵中值为0的元素所在的行和列设置为0, in-place O(1)space O(mn) time

时间:2015-04-09 22:00:53      阅读:128      评论: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?

public class Solution {
    public void setZeroes(int[][] matrix) {
        
        int m=matrix.length;
        if(m==0)
            return;
        int n=matrix[0].length;
        if(n==0)
            return;
        boolean preZeros=false;
        boolean curZeros=false;
        for(int i=0;i<m;i++)
        {
            //test if this row has zeros.
            for(int j=0;j<n;j++)
            {
                if(matrix[i][j]==0)
                {
                    for(int k=0;k<i;k++)
                        matrix[k][j]=0;
                    curZeros=true;
                }
            }
            //fill the zeros along coloum.
            if(i>0)
            {
                for(int j=0;j<n;j++)
                {
                    if(matrix[i-1][j]==0)
                    {
                        matrix[i][j]=0;
                    }
                }
            }
            //if pre row has zeros, fill zeros with that row.
            if(preZeros)
            {
                for(int j=0;j<n;j++)
                {
                    matrix[i-1][j]=0;
                }
            }
            preZeros=curZeros;
            curZeros=false;
        }
        
        if(preZeros)
        {
            for(int j=0;j<n;j++)
            {
                matrix[m-1][j]=0;
            }
        }
    }
}



将矩阵中值为0的元素所在的行和列设置为0, in-place O(1)space O(mn) time

标签:

原文地址:http://blog.csdn.net/smartxxyx/article/details/44964611

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