当前位置: 首页 > news >正文

Leetcode Hot 100刷题记录 -Day14(矩阵置0)

矩阵置0

问题描述:

        给定一个 m x n 的矩阵,如果一个元素为 ,则将其所在行和列的所有元素都设为 0。

示例 1:

输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]

示例 2:

输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

思路分析:

        先第一次扫描数组,找到为0的元素,然后将其所在的行和列进行标记(boolean true为0);再次扫描数组,将标记为true的数组元素置为0。

//提交版
class Solution {public int[][] setZeroes(int[][] matrix) {//矩阵的行数int m = matrix.length;//矩阵的列数int n = matrix[0].length;boolean[] row = new boolean[m];boolean[] col = new boolean[n];for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (matrix[i][j] == 0) {row[i] = true;col[j] = true;}}}for (int k = 0; k < m; k++) {for (int l = 0; l < n; l++) {if (row[k] || col[l]) {matrix[k][l] = 0;}}}return matrix;}
}//带有输入输出版本
import java.util.Arrays;public class hot15_setZeroes {public int[][] setZeroes(int[][] matrix) {//矩阵的行数int m = matrix.length;//矩阵的列数int n = matrix[0].length;boolean[] row = new boolean[m];boolean[] col = new boolean[n];for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (matrix[i][j] == 0) {row[i] = true;col[j] = true;}}}for (int k = 0; k < m; k++) {for (int l = 0; l < n; l++) {if (row[k] || col[l]) {matrix[k][l] = 0;}}}return matrix;}public static void main(String[] args){int[][] matrix = {{1,1,1},{1,0,1},{1,1,1}};System.out.println("输入:" + Arrays.deepToString(matrix));hot15_setZeroes hot15SetZeroes = new hot15_setZeroes();int[][] result = hot15SetZeroes.setZeroes(matrix);System.out.println("输出:" + Arrays.deepToString(result));}
}
http://www.lryc.cn/news/441445.html

相关文章:

  • 每日刷题(算法)
  • 大牛直播SDK核心音视频模块探究
  • gin配置swagger文档
  • 基于ssm的快餐店点餐系统设计与实现
  • 集合框架底层使用了什么数据结构
  • Activiti7《第二式:破剑式》——工作流中的以柔克刚
  • docker快速搭建kafka
  • 基于 onsemi NCV78343 NCV78964的汽车矩阵式大灯方案
  • OpenAl o1论文:Let’s Verify Step by Step 快速解读
  • Errorresponsefromdaemon:toomanyrequests:Youhavereachedyourpullratelimit.
  • [2025]医院健康陪诊系统(源码+定制+服务)
  • Golang | Leetcode Golang题解之第405题数字转换为十六进制数
  • VB中如何使用正则表达式(Regular Expressions)
  • Docker FROM 指定基础镜像
  • 19:I2C一:程序模拟I2C通信时序
  • 最佳实践 · MySQL 分区表实战指南
  • 详细介绍 Redis 列表的应用场景
  • 游戏如何检测加速外挂
  • 【STM32 HAL库】OLED显示模块
  • Redis---卸载Redis
  • 《C++模板元编程实战》阅读记录
  • pybind11 学习笔记
  • 36.贪心算法3
  • htop(1) command
  • ODrive学习——添加485编码器支持
  • 在OSX上: 使用brew安装nginx 后,在通过编译安装第三方模块
  • C++初阶学习第六弹------标准库中的string类
  • Linux基础-Makefile的编写、以及编写第一个Linux程序:进度条(模拟在 方便下载的同时,更新图形化界面)
  • 华为云DevSecOps和DevOps
  • RESTful API设计中的GET与POST:何时及为何成为首选?