抬头仰望星空,是否能发现自己的渺小。

伪斜杠青年

人们总是混淆了欲望和理想

Leetcode 54. 螺旋矩阵

54. 螺旋矩阵

解法:按层模拟

思路:这题并不难,选择一个好理解的思路进行练习即可。

这个思路主要是这张图:(来自LeetCode官方题解)

详细请移步:https://leetcode-cn.com/problems/spiral-matrix/solution/luo-xuan-ju-zhen-by-leetcode-solution/

class Some54Solution {

fun spiralOrder(matrix: Array<IntArray>): List<Int> {
if (matrix.isEmpty()) return arrayListOf()
val rows = matrix.size
val columns = matrix[0].size
var left = 0
var right = columns - 1
var top = 0
var bottom = rows - 1

val res = arrayListOf<Int>()
while (left <= right && top <= bottom) {
for (column in left..right) {
res.add(matrix[top][column])
}
for (row in top + 1..bottom) {
res.add(matrix[row][right])
}
if (left < right && top < bottom) {
for (column in right - 1 downTo left) {
res.add(matrix[bottom][column])
}
for (row in bottom - 1 downTo top + 1) {
res.add(matrix[row][left])
}
}
left++
right--
top++
bottom--
}
return res
}

}

fun main() {
val array = arrayOf(
intArrayOf(1, 2, 3, 4),
intArrayOf(12, 13, 14, 5),
intArrayOf(11, 16, 15, 6),
intArrayOf(10, 9, 8, 7)
)
Some54Solution().spiralOrder(array).forEach {
print("$it ")
}
}


本站由以下主机服务商提供服务支持:

0条评论

发表评论