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

Jan 20 - Set Matrix Zeros; Array;

时间:2016-01-21 06:56:43      阅读:128      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!