您的位置:首页 > 其它

LeetCode 73 Set Matrix Zeroes

2014-06-18 14:59 483 查看
Given a m  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 row=matrix.length;
        int column=matrix[0].length;
        if(matrix==null||row<1) return ;
        boolean[] rowflag= new boolean[row];
        boolean[] colflag= new boolean[column];
        for(int i=0;i<row;i++){
        	for(int j=0;j<column;j++){
        		if(matrix[i][j]==0){
        			rowflag[i]=true;
        			colflag[j]=true;
        		}
        	}
        }
        for(int i=0;i<row;i++){
        	if(rowflag[i]){
        		for(int j=0;j<column;j++){
        			matrix[i][j]=0;
        		}
        	}
        }
        for(int i=0;i<column;i++){
        	if(colflag[i]){
        		for(int j=0;j<row;j++){
        			matrix[j][i]=0;
        		}
        	}
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: