Set Matrix Zeroes

描述

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?

分析

O(m+n)空间的方法很简单,设置两个bool数组,记录每行和每列是否存在0。

想要常数空间,可以复用第一行和第一列。

代码1

  1. // Set Matrix Zeroes
  2. // 时间复杂度O(m*n),空间复杂度O(m+n)
  3. public class Solution {
  4. public void setZeroes(int[][] matrix) {
  5. final int m = matrix.length;
  6. final int n = matrix[0].length;
  7. boolean[] row = new boolean[m]; // 标记该行是否存在0
  8. boolean[] col = new boolean[n]; // 标记该列是否存在0
  9. for (int i = 0; i < m; ++i) {
  10. for (int j = 0; j < n; ++j) {
  11. if (matrix[i][j] == 0) {
  12. row[i] = col[j] = true;
  13. }
  14. }
  15. }
  16. for (int i = 0; i < m; ++i) {
  17. if (row[i]) Arrays.fill(matrix[i], 0);
  18. }
  19. for (int j = 0; j < n; ++j) {
  20. if (col[j]) {
  21. for (int i = 0; i < m; ++i) {
  22. matrix[i][j] = 0;
  23. }
  24. }
  25. }
  26. }
  27. }

代码2

  1. // Set Matrix Zeroes
  2. // 时间复杂度O(m*n),空间复杂度O(1)
  3. public class Solution {
  4. public void setZeroes(int[][] matrix) {
  5. final int m = matrix.length;
  6. final int n = matrix[0].length;
  7. boolean row_has_zero = false; // 第一行是否存在 0
  8. boolean col_has_zero = false; // 第一列是否存在 0
  9. for (int i = 0; i < n; i++)
  10. if (matrix[0][i] == 0) {
  11. row_has_zero = true;
  12. break;
  13. }
  14. for (int i = 0; i < m; i++)
  15. if (matrix[i][0] == 0) {
  16. col_has_zero = true;
  17. break;
  18. }
  19. for (int i = 1; i < m; i++)
  20. for (int j = 1; j < n; j++)
  21. if (matrix[i][j] == 0) {
  22. matrix[0][j] = 0;
  23. matrix[i][0] = 0;
  24. }
  25. for (int i = 1; i < m; i++)
  26. for (int j = 1; j < n; j++)
  27. if (matrix[i][0] == 0 || matrix[0][j] == 0)
  28. matrix[i][j] = 0;
  29. if (row_has_zero)
  30. for (int i = 0; i < n; i++)
  31. matrix[0][i] = 0;
  32. if (col_has_zero)
  33. for (int i = 0; i < m; i++)
  34. matrix[i][0] = 0;
  35. }
  36. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/array/set-matrix-zeroes.html