用上, 下, 左, 右四個指標來移動, 當left <= right -1且up <= down - 1時繼續執行以下動作
上排: 從left到right, 依序將數值放到res, 並遞增up
右排: 從up到down, 依序將數值放到res, 並遞減right
下排: 從right到left, 依序將數值放到res, 並遞減down
左排: 從down到up, 依序將數值放到res, 並遞增left
測試計算複雜度
3.程式碼
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) {
return res;
}
int m = matrix.size();
int n = matrix[0].size();
int index = 0, up = 0, right = n, left = 0, down = m;
while (left <= right- 1 && up <= down - 1) {
for (int i = left; i < right; i++) {
if (res.size() < m * n) {
res.push_back(matrix[up][i]);
}
}
up++;
for (int i = up; i < down; i++) {
if (res.size() < m * n) {
res.push_back(matrix[i][right - 1]);
}
}
right--;
for (int i = right - 1; i >= left; i--) {
if (res.size() < m * n) {
res.push_back(matrix[down - 1][i]);
}
}
down--;
for (int i = down - 1; i >= up; i--) {
if (res.size() < m * n) {
res.push_back(matrix[i][left]);
}
}
left++;
}
return res;
}
};