image.png

思路

方法 1:额外存储空间方法

image.png

code

  1. public void setZeroes(int[][] matrix) {
  2. Set<Integer> rowSet = new HashSet<>();
  3. Set<Integer> columnSet = new HashSet<>();
  4. int rows = matrix.length;
  5. int columns = matrix[0].length;
  6. for(int i=0;i<rows;i++)
  7. for(int j=0;j<columns;j++){
  8. if(matrix[i][j]==0){
  9. rowSet.add(i); //加到集合中去
  10. columnSet.add(j);
  11. }
  12. }
  13. for(int i=0;i<rows;i++){
  14. for(int j=0;j<columns;j++){
  15. if(rowSet.contains(i)||columnSet.contains(j)){
  16. matrix[i][j]=0; //进行更新
  17. }
  18. }
  19. }
  20. }

方法2 不使用额外空间的解法

image.png

  1. class Solution {
  2. public void setZeroes(int[][] matrix) {
  3. Boolean isCol = false;
  4. int R = matrix.length;
  5. int C = matrix[0].length;
  6. for (int i = 0; i < R; i++) {
  7. // Since first cell for both first row and first column is the same i.e. matrix[0][0]
  8. // We can use an additional variable for either the first row/column.
  9. // For this solution we are using an additional variable for the first column
  10. // and using matrix[0][0] for the first row.
  11. if (matrix[i][0] == 0) {
  12. isCol = true;
  13. }
  14. for (int j = 1; j < C; j++) {
  15. // If an element is zero, we set the first element of the corresponding row and column to 0
  16. if (matrix[i][j] == 0) {
  17. matrix[0][j] = 0;
  18. matrix[i][0] = 0;
  19. }
  20. }
  21. }
  22. for (int i = 1; i < R; i++) {
  23. for (int j = 1; j < C; j++) {
  24. if (matrix[i][0] == 0 || matrix[0][j] == 0) {
  25. matrix[i][j] = 0;
  26. }
  27. }
  28. }
  29. // See if the first row needs to be set to zero as well
  30. if (matrix[0][0] == 0) {
  31. for (int j = 0; j < C; j++) {
  32. matrix[0][j] = 0;
  33. }
  34. }
  35. if (isCol) {
  36. for (int i = 0; i < R; i++) {
  37. matrix[i][0] = 0;
  38. }
  39. }
  40. }
  41. }