赞
踩
example
input : matrix = [[1,1,1],[1,0,1],[1,1,1]]
output : [[1,0,1],[0,0,0],[1,0,1]]
input : matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
output : [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
思路1 辅助标记
思路2 辅助数组
思路1代码
public class Solution1 { public void setZeroes(int[][] matrix) { boolean flagRow = false; boolean flagCol = false; for (int i = 0; i < matrix[0].length; i++) { if (matrix[0][i] == 0) { flagRow = true; } } for (int j = 0; j < matrix.length; j++) { if (matrix[j][0] == 0) { flagCol = true; } } System.out.println("flagRow : " + flagRow); System.out.println("flagCol : " + flagCol); System.out.println("set flag---------"); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j] + "\t "); } System.out.println(); } System.out.println("set zero---------"); for (int i = 1; i < matrix.length; i++) { for (int j = 1; j < matrix[i].length; j++) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } } for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j] + "\t "); } System.out.println(); } System.out.println("judge first ---------"); if (flagRow) { for (int i = 0; i < matrix[0].length; i++) { matrix[0][i] = 0; } } if (flagCol) { for (int j = 0; j < matrix.length; j++) { matrix[j][0] = 0; } } } }
思路2代码
public class Solution2 { // 辅助数组 public void setZeroes(int[][] matrix) { boolean[] flagRow = new boolean[matrix.length]; boolean[] flagCol = new boolean[matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 0) { flagRow[i] = true; flagCol[j] = true; } } } System.out.println("set zero---------"); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (flagRow[i] || flagCol[j]) { matrix[i][j] = 0; } } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。