LeetCode 59. 螺旋矩阵 II

题目描述

59. 螺旋矩阵 II

考察公司:小米

image-20230305150635551

思路分析

模拟法

image-20250510201946574

参考代码

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
37
38
39
40
41
42
43
44
45
46
func generateMatrix(n int) [][]int {
	matrix := make([][]int, n)
	for i := range matrix {
		matrix[i] = make([]int, n)
	}

	top, bottom := 0, n-1
	left, right := 0, n-1
	num := 1

	for top <= bottom && left <= right {
		// 从左到右填充 top 行
		for i := left; i <= right; i++ {
			matrix[top][i] = num
			num++
		}
		top++

		// 从上到下填充 right 列
		for i := top; i <= bottom; i++ {
			matrix[i][right] = num
			num++
		}
		right--

		// 从右到左填充 bottom 行
		if top <= bottom {
			for i := right; i >= left; i-- {
				matrix[bottom][i] = num
				num++
			}
			bottom--
		}

		// 从下到上填充 left 列
		if left <= right {
			for i := bottom; i >= top; i-- {
				matrix[i][left] = num
				num++
			}
			left++
		}
	}

	return matrix
}
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
37
38
39
40
41
func generateMatrix(n int) [][]int {
	matrix := make([][]int, n)
	for i := range matrix {
		matrix[i] = make([]int, n)
	}

	top, bottom, left, right := 0, n-1, 0, n-1
	num := 1

	for num <= n*n {
		// 从左到右填一行
		for i := left; i <= right; i++ {
			matrix[top][i] = num
			num++
		}
		top++

		// 从上到下填一列
		for i := top; i <= bottom; i++ {
			matrix[i][right] = num
			num++
		}
		right--

		// 从右到左填一行
		for i := right; i >= left; i-- {
			matrix[bottom][i] = num
			num++
		}
		bottom--

		// 从下到上填一列
		for i := bottom; i >= top; i-- {
			matrix[i][left] = num
			num++
		}
		left++
	}

	return matrix
}
  • 时间复杂度:O(n²),因为需要填充 n² 个位置。
  • 空间复杂度:O(n²),使用了一个 n×n 的矩阵。

➡️ 点击查看 Java 题解

1
write your code here

相似题目

image-20250510202249348

本文作者:
本文链接: https://hgnulb.github.io/blog/2025/80898555
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!