按层模拟:
时间复杂度:,m和n是行数和列数
空间复杂度:,用到的left,right,top,bottom数量有限,res是结果,所以是
首先判断数组,空数组直接返回
难点在于边界问题,在循环中需要判断 top<= bottom 和 left <= right,防止重复插入
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int row = matrix.size();
if (!row) return {};
int col = matrix[0].size();
if (!col) return {};
int left = 0, right = col - 1;
int top = 0, bottom = row - 1;
vector<int> res;
res.reserve(row * col);
while (left <= right && top <= bottom) {
for (int i = left; i <= right; ++i) {
res.push_back(matrix[top][i]);
}
++top;
for (int i = top; i <= bottom; ++i) {
res.push_back(matrix[i][right]);
}
--right;
if (top <= bottom) {
for (int i = right; i >= left; --i) {
res.push_back(matrix[bottom][i]);
}
--bottom;
}
if (left <= right) {
for (int i = bottom; i >= top; --i) {
res.push_back(matrix[i][left]);
}
++left;
}
}
return res;
}
};
博客提及力扣按层模拟算法,分析其时间复杂度与行数、列数相关,空间复杂度因用到的变量数量有限。还指出要先判断数组是否为空,空数组直接返回,循环中需判断top<= bottom和left <= right,避免重复插入。
1004

被折叠的 条评论
为什么被折叠?



