73. 矩阵置零

可以选择遍历两遍matrix,一遍记录哪些行哪些列需要置0,一遍置0

O(1)空间复杂度的做法:

首先设置两个boolean型变量记录第0行和第0列是否需要置0

然后用第0行和第0列记录需要置0的行和列

java 复制代码
class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        boolean row0 = false, col0 = false;
        for (int j = 0; j < n; j++) {
            if (matrix[0][j] == 0) row0 = true;
        }
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0) col0 = true;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0) matrix[0][j] = matrix[i][0] = 0;
            }
        }
        // set 0
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
            }
        }
        if (row0) {
            for (int j = 0; j < n; j++) {
                matrix[0][j] = 0;
            }
        }
        if (col0) {
            for (int i = 0; i < m; i++) {
                matrix[i][0] = 0;
            }
        }
    }
}
相关推荐
mit6.8244 小时前
bfs|栈
算法
CoderYanger5 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz5 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
稚辉君.MCA_P8_Java5 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*6 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
.YM.Z7 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong3457 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
百***48077 小时前
【Golang】slice切片
开发语言·算法·golang
墨染点香7 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展
做怪小疯子7 小时前
LeetCode 热题 100——链表——反转链表
算法·leetcode·链表