73. Set Matrix Zeroes
iven a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
//如果某个元素为0,则把该元素所在的行和列都设为0。本题用了o(1)的space
//先看第一行第一列是不是有0,用fr,fc记录。扫描剩下的元素,如果遇到0,就把对应的第一行第一列元素赋值为0,如matrix[2,3]为0,就把matrix[2,0]和matrix[0,3]设为0。
//从1,1开始扫描,如果元素对应的第一行或第一列元素为0,则把它也设为0
//处理第一行和第一列
public void setZeroes(int[][] matrix) {
boolean fr = false;
boolean fc = false;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
if (i == 0)
fr = true;
if (j == 0)
fc = true;
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for (int i = 1; i < matrix.length; i++) {
for (int j = 1; j < matrix[0].length; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if(fr) {
for(int j = 0; j < matrix[0].length; j++) {
matrix[0][j] = 0;
}
}
if(fc) {
for(int j = 0; j < matrix.length; j++) {
matrix[j][0] = 0;
}
}
}
分类:
leetCode hot 100
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix