118.Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

 给定一个二维数组,把原始数组中的那些为0的元素所在的行和列的元素都设为0.

 Step1:用两个集合分别表示原始数组中0元素的所在的行和列;
 Step2:遍历二维数组填充步骤1中的两个集合;
 Step3:获取两个集合中的元素把行和列上的元素都置为0。

/**
	 * 给定一个二维数组,把原始数组中的那些为0的元素所在的行和列的元素都设为0.
	 * Step1:用两个集合分别表示原始数组中0元素的所在的行和列;
	 * Step2:遍历二维数组填充步骤1中的两个集合;
	 * Step3:获取两个集合中的元素把行和列上的元素都置为0。
	 * @date 20160505
	 * @param matrix
	 */
	public void setZeroes(int[][] matrix) {
        int rowSize = matrix.length;
        if(rowSize <= 0){
        	return;
        }
        int colSize = matrix[0].length;
        /*Step1:用两个集合分别表示原始数组中0元素的所在的行和列*/
        Set<Integer> rowSet = new HashSet<Integer>();
        Set<Integer> colSet = new HashSet<Integer>();
        /*Step2:遍历二维数组填充步骤1中的两个集合*/
        for(int i = 0;i<rowSize;i++){
        	for(int j=0;j<colSize;j++){
        		if(matrix[i][j] == 0){
        			rowSet.add(i);
        			colSet.add(j);
        		}
        	}
        }
        /*Step3:获取两个集合中的元素把行和列上的元素都置为0*/
        for(int row : rowSet){
        	for(int j=0;j<colSize;j++){
        		matrix[row][j] = 0;
        	}
        }
        
        for(int col : colSet){
        	for(int i=0;i<rowSize;i++){
        		matrix[i][col] = 0;
        	}
        }
        
    }



你可能感兴趣的:(118.Set Matrix Zeroes)