leetcode 54题 螺旋矩阵
给你一个 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]
思路
按层数输出
代码
/**
* @param {number[][]} matrix
* @return {number[]}
*/
function spiralOrder(matrix) {
// 按层数输出
const order = [];
if (matrix.length === 0 || matrix[0].length === 0) {
return order;
}
const rows = matrix.length;
const columns = matrix[0].length;
let left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
// 上左到上右
for (let start = left; start <= right; start++) {
order.push(matrix[top][start]);
}
// 右上到右下
for (let start = top + 1; start <= bottom; start++) {
order.push(matrix[start][right]);
}
if (left < right && top < bottom) {
// 下右到下左
for (let start = right - 1; start > left; start--) {
order.push(matrix[bottom][start]);
}
// 左下到左上
for (let start = bottom; start > top; start--) {
order.push(matrix[start][left]);
}
}
top++;
left++;
bottom--;
right--;
}
return order;
}
复杂度分析:
- 时间复杂度: O(N^2)
- 空间复杂度:O(N)