首页 > 其他 > 详细

Jan 20 - Set Matrix Zeros; Array;

时间:2016-01-21 06:55:03      阅读:222      评论:0      收藏:0      [点我收藏+]

Use additional O(m+n) space, simple improvement. Two array, one is of size row, to store the status of each row, whether there is a 0 element in the row. Similarly, the other array of size col, storing the status of each column that whether there is 0 element in the column. Then traverse the arrays, if the current element is true, which represents that there are at least one 0 element in the row(column). Then set all the elements in the row(column) to be zero.

Code:

public class Solution {
    public void setZeroes(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        boolean[] isZeroColumn = new boolean[col];
        boolean[] isZeroRow = new boolean[row];
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(matrix[i][j]==0) {
                    isZeroRow[i] = true;
                    isZeroColumn[j] = true;
                }
            }
        }
        for(int i = 0; i < row; i++){
            if(isZeroRow[i]){
                for(int j = 0; j < col; j++) matrix[i][j] = 0;
            }
        }
        for(int i = 0; i < col; i++){
            if(isZeroColumn[i]){
                for(int j = 0; j < row; j++) matrix[j][i] = 0;
            }
        }
    }
}

 

Jan 20 - Set Matrix Zeros; Array;

原文:http://www.cnblogs.com/5683yue/p/5147102.html

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