2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_73.java 1.88 KB
一键复制 编辑 原始数据 按行查看 历史
CG国斌 提交于 2020-11-01 10:02 . 中等难度:字符串 & 链表
package com.hit.basmath.interview.top_interview_questions.medium_collection.array_and_strings;
/**
* 73. 矩阵置零
* <p>
* 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
* <p>
* 示例 1:
* <p>
* 输入:
* [
*   [1,1,1],
*   [1,0,1],
*   [1,1,1]
* ]
* 输出:
* [
*   [1,0,1],
*   [0,0,0],
*   [1,0,1]
* ]
* <p>
* 示例 2:
* <p>
* 输入:
* [
*   [0,1,2,0],
*   [3,4,5,2],
*   [1,3,1,5]
* ]
* 输出:
* [
*   [0,0,0,0],
*   [0,4,5,0],
*   [0,3,1,0]
* ]
* <p>
* 进阶:
* <p>
* 一个直接的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。
* 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
* 你能想出一个常数空间的解决方案吗?
*/
public class _73 {
public void setZeroes(int[][] matrix) {
boolean firstRow = false, firstColumn = 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) firstRow = true;
if (j == 0) firstColumn = 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 (firstRow) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[0][j] = 0;
}
}
if (firstColumn) {
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助