友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

73. 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.

Example 1:

Input:
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output:
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:

Input:
[
  [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]
]

Follow up:

  • A straight forward solution using O(m__n) 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?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Set Matrix Zeroes.
     *
     * Memory Usage: 50.4 MB, less than 5.71% of Java online submissions for Set Matrix Zeroes.
     */
    public void setZeroes(int[][] matrix) {
        if (Objects.isNull(matrix) || matrix[0].length == 0) {
            return;
        }
        /**
         * 0 all is 0;
         * 1 row is 0;
         * 2 column is 0;
         * 3 is not 0;
         */
        int flag = 3;
        int value = matrix[0][0];
        if (value == 0) {
            flag = 0;
        }
        int column = matrix.length;
        int row = matrix[0].length;
        for (int i = 0; i < column; i++) {
            for (int j = 0; j < row; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                    if (i == 0 && j > 0 && flag != 0) {
                        flag = 1;
                    }
                    if (i > 0 && j == 0 && flag != 0) {
                        if (flag == 1) {
                            flag = 0;
                        } else {
                            flag = 2;
                        }
                    }
                }
            }
        }
//        printMatrix(matrix);
        for (int i = 1; i < column; i++) {
            if (matrix[i][0] == 0) {
                Arrays.fill(matrix[i], 0);
            }
        }
        for (int j = 1; j < row; j++) {
            if (matrix[0][j] == 0) {
                for (int i = 0; i < column; i++) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (flag == 0) {
            Arrays.fill(matrix[0], 0);
            for (int i = 0; i < column; i++) {
                matrix[i][0] = 0;
            }
        } else if (flag == 1) {
            Arrays.fill(matrix[0], 0);
        } else if (flag == 2) {
            for (int i = 0; i < column; i++) {
                matrix[i][0] = 0;
            }
        }
    }