public class Solution { public void setZeroes(int[][] matrix) { int m = matrix.length, n = matrix[0].length; boolean colZero = false; boolean rowZero =false; for(int i = 0; i < m; ++i){ for(int j = 0; j < n; ++ j){ if(matrix[i][j] == 0){ if(i == 0) rowZero = true; if(j == 0) colZero = true; matrix[i][0] = 0; matrix[0][j] = 0; } } } for(int j =1; j < n; ++ j){ if(matrix[0][j] == 0){ for (int i = 0; i < m; ++i){ matrix[i][j] = 0; } } } for(int i =1; i < m; ++ i){ if(matrix[i][0] == 0){ for (int j = 0; j < n; ++j){ matrix[i][j] = 0; } } } if(colZero){ for(int i = 0; i< m; ++i){ matrix[i][0] = 0; } } if(rowZero){ for (int j = 0 ; j< n; ++j){ matrix[0][j] = 0; } } } }此外我们可以记录相应的0的位置,我这其实是浪费空间了,其实可以优化到O(m+n)的空间
public void setZeroes1(int[][] matrix) { int m = matrix.length, n = matrix[0].length; class Node { int x; int y; public Node(int x, int y) { this.x = x; this.y = y; } } List<Node> nodes = new LinkedList<Node>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) { nodes.add(new Node(i, j)); } } } for (Node node : nodes) { for (int i = 0; i < m; i++) { matrix[i][node.y] = 0; } for (int j = 0; j < n; ++j) { matrix[node.x][j] = 0; } } }
原文:http://blog.csdn.net/youmengjiuzhuiba/article/details/44902431