【数据结构入门_数组】矩阵置零

题目链接:leetcoede 73. 矩阵置零

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0’s.

You must do it in place.

在这里插入图片描述

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

在这里插入图片描述

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

Constraints:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -231 <= matrix[i][j] <= 231 - 1

Follow up:

  • A straightforward 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?

思路:

  • 做法1.暴力 : 复制一个一摸一样的数组,在原数组里遇到0,就将新数组对应的行列都赋值为0,最后输出行数组就是答案。时间复杂度为O(n3),空间复杂度也很高,这不是一个好方法。
  • 做法2. 开两个一维数组,用来存放每行和每列是否需要被设置为0,时间复杂度为O(n2)
  • 做法3.,用第一行和第一列来代替做法2的额外数组,来存放对应行和列是否需要被赋值为0的信息,然后用两个变量来表示第一行和第一列本身是否需要被赋值为0。时间复杂度为O(n2),但空间复杂度只有O(1)

做法3代码实现:

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        // 特判,如果行列为空
        if(matrix.empty() || matrix[0].empty()) return;

        // n行数 m列数 r0第0行是否有0 c0类似
        int n = matrix.size(), m = matrix[0].size();
        int r0 = 1, c0 = 1;

        // 判断第0行和第0列
        for(int j = 0; j < m; j ++ ){
            if(matrix[0][j] == 0) r0 = 0;
        }
        for(int i = 0; i < n; i ++ ){
            if(matrix[i][0] == 0) c0 = 0;
        }

        // 判断中间
        for(int i = 1; i < n; i ++ ){
            for(int j = 1; j < m; j ++ ){
                if(matrix[i][j] == 0){
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        

        // 给中间部分赋值
        for(int i = 1; i < n; i ++ ){
            if(matrix[i][0] == 0){
                for(int j = 0; j < m; j ++ ){
                    matrix[i][j] = 0;
                }
            }
        }
        for(int j = 1; j < m; j ++ ){
            if(matrix[0][j] == 0){
                for(int i = 0; i < n; i ++ ){
                    matrix[i][j] = 0;
                }
            }
        }
        //给第一行和第一列赋值
        if(!r0)
            for(int j = 0; j < m; j ++)
                matrix[0][j] = 0;
        if(!c0)
            for(int i = 0; i < n; i ++)
                matrix[i][0] = 0;

    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值