【Day 13】189.轮转数组
文章目录
- 189.轮转数组
- 题目:
- 思路:
- 代码实现(Go):
189.轮转数组
题目:
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
思路:
上下左右转圈圈:
从左到右,顶部一层遍历完往下移一位,top++
;
从上到下,遍历完右侧往左移一位,right--
;
从右到左,判断top <= bottom,遍历完底部上移,bottom--
;
从下到上,判断left <= right,遍历完左侧右移,left++
;
后两步需要判断的原因:
在循环内部,上边界和右边界先被使用并收缩(top++、right--)
当到达下边界或左边界时,边界可能已经交错了
top > bottom 或 left > right
需要判断才能安全遍历
代码实现(Go):
详细注解:
// package main// import "fmt"func spiralOrder(matrix [][]int) []int {// 矩阵为空或矩阵行为空(行存在,但列为空,也就是空行),1 <= m,n <= 10,所以可不写if len(matrix) == 0 || len(matrix[0]) == 0 {return []int{}}// 获取矩阵行数和列数m, n := len(matrix), len(matrix[0])// 定义四个边界top, bottom := 0, m-1 // 上下边界left, right := 0, n-1 // 左右边界res := []int{} // 用于存储结果// 当边界没有交错时,继续循环for top <= bottom && left <= right {// 1)上边界:从左到右遍历 top 行for j := left; j <= right; j++ {res = append(res, matrix[top][j])}top++ // 上边界收缩,下一圈不再遍历这行// 2)右边界:从上到下遍历 right 列for i := top; i <= bottom; i++ {res = append(res, matrix[i][right])}right-- // 右边界收缩// 3)下边界:从右到左遍历 bottom 行// 注意需要判断 top <= bottom,防止重复遍历单行if top <= bottom { // 只有当 top <= bottom 时,才遍历底部一行,并且收缩下边界for j := right; j >= left; j-- {res = append(res, matrix[bottom][j])}bottom-- // 下边界收缩}// 4)左边界:从下到上遍历 left 列// 注意需要判断 left <= right,防止重复遍历单列if left <= right { // 只有当 left <= right 时,才遍历左边一列,并且收缩左边界for i := bottom; i >= top; i-- {res = append(res, matrix[i][left])}left++ // 左边界收缩}}return res
}// func main() {
// matrix := [][]int{
// {1, 2, 3},
// {4, 5, 6},
// {7, 8, 9},
// }
// fmt.Println(spiralOrder(matrix)) // 输出: [1 2 3 6 9 8 7 4 5]
// }
无注释:
// package main// import "fmt"func spiralOrder(matrix [][]int) []int {if len(matrix) == 0 || len(matrix[0]) == 0 {return []int{}}m, n := len(matrix), len(matrix[0])top, bottom := 0, m-1left, right := 0, n-1res := []int{}for top <= bottom && left <= right {for j := left; j <= right; j++ {res = append(res, matrix[top][j])}top++for i := top; i <= bottom; i++ {res = append(res, matrix[i][right])}right--if top <= bottom {for j := right; j >= left; j-- {res = append(res, matrix[bottom][j])}bottom--}if left <= right {for i := bottom; i >= top; i-- {res = append(res, matrix[i][left])}left++}}return res
}// func main() {
// matrix := [][]int{
// {1, 2, 3},
// {4, 5, 6},
// {7, 8, 9},
// }
// fmt.Println(spiralOrder(matrix)) // 输出: [1 2 3 6 9 8 7 4 5]
// }