lurenaa的博客

实现

不要通过一个i,j加减来移动添加,不好控制位置。使用范围框住来添加方便清晰很多。

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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> nums;
if(matrix.empty()) return nums;
int top = 0,
bottom = matrix.size() - 1,
left = 0,
right = matrix[0].size() - 1;
while(1) {
for(int j = left ; j <= right; ++j)
nums.push_back(matrix[top][j]);
if(++top > bottom) break;
for(int i = top; i <= bottom; ++i)
nums.push_back(matrix[i][right]);
if(--right < left) break;
for(int j = right; j >= left; --j)
nums.push_back(matrix[bottom][j]);
if(--bottom < top) break;
for(int i = bottom; i >= top; --i)
nums.push_back(matrix[i][left]);
if(++left > right) break;
}
return nums;
}
};

Accepted

22/22 cases passed (0 ms)

Your runtime beats 100 % of cpp submissions

Your memory usage beats 5.04 % of cpp submissions (8.9 MB)