Set Matrix Zeroes

Set Matrix Zeroes

leetcode73

题目:

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?

空间复杂度 O(m*n) 或 O(m+n) 比较容易实现,难度在于实现空间复杂度 O(1) 的算法。

思路:

空间复杂度 O(1) 代表我们不能创建行/列长度的状态数组,考虑借用输入数组存放状态变量。例如,选取第1列存放状态变量,在这之前先将第一列的状态保存下来。

class Solution {
    public void setZeroes(int[][] matrix) {
        // col0用来保存第一列状态
        int col0 = 1;
        int rows = matrix.length;
        int cols = matrix[0].length;
        for (int row = 0; row < rows; row++) {
            if(matrix[row][0] == 0)
                col0 = 0;
            for(int col = 1; col < cols; col++){
                // 将状态保存到第一列
                if(matrix[row][col] == 0){
                    matrix[row][0] = 0;
                    matrix[0][col] = 0;
                }
            }
        }

        for (int row = rows-1; row >= 0 ; row--) {
            for (int col = cols-1; col >= 1 ; col--) {
                if(matrix[0][col] == 0 || matrix[row][0] == 0)
                    matrix[row][col] = 0;
            }
            // 还原第一列状态
            if(col0 == 0)
                matrix[row][0] = 0;
        }
        return;
    }
}

算法只创建了常数个变量,空间复杂度为 O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值