59. 螺旋矩阵 II

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

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
28
29
30
31
32
33
34
35
36
class Solution {
func generateMatrix(_ n: Int) -> [[Int]] {
var matrix = [[Int]].init(repeating: [Int].init(repeating: 0, count: n), count: n)
var left = 0, right = n - 1, top = 0, bottom = n - 1
var num = 1
while left <= right && top <= bottom {
for col in left ... right {
matrix[top][col] = num
num += 1
}
if (top + 1 <= bottom) {
for row in (top+1) ... bottom {
matrix[row][right] = num
num += 1
}
}

if left < right && top < bottom {
for col in stride(from: right-1, to: left, by: -1) {
matrix[bottom][col] = num
num += 1
}

for row in stride(from: bottom, to: top, by: -1) {
matrix[row][left] = num
num += 1
}
}
left += 1
right -= 1
top += 1
bottom -= 1
}
return matrix
}
}

59. 螺旋矩阵 II
https://pisces34.github.io/2021/10/10/leetcode/59/
发布于
2021年10月10日
许可协议