73. 矩阵置零

题目链接:https://leetcode-cn.com/problems/set-matrix-zeroes/

解题思路

先遍历找到矩阵中0的位置,放入一维数组。
遍历一维数组中变化的值,下标除以矩阵宽度即为所在行号。

执行用时:88 ms, 在所有 Swift 提交中击败了100.00%的用户
内存消耗:14.4 MB, 在所有 Swift 提交中击败了16.28%的用户

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
func setZeroes(_ matrix: inout [[Int]]) {
var count = 0
let r = matrix.count, c = matrix[0].count
var arr = [Int].init(repeating: -1, count: r*c)
for i in 0 ..< r {
for j in 0 ..< c {
if matrix[i][j] == 0 {
//下标为序号,除以宽度即为行号
//数组值为列号
arr[count] = count % c
}
count += 1
}
}
for row in 0 ..< r*c {
if arr[row] != -1 {
for i in 0 ..< c {
matrix[row/c][i] = 0
}
for j in 0 ..< r {
matrix[j][arr[row]] = 0
}
}
}
}
}

73. 矩阵置零
https://pisces34.github.io/2021/09/27/leetcode/73/
发布于
2021年9月27日
许可协议