从里到外一层一层剥洋葱即可,注意最后只剩一行或者一列的时候不要重复访问。时间复杂度O(n),空间复杂度O(1),代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> spiralOrder(vector<vector<int>>& matrix) { | |
int m = matrix.size(), n = m? matrix[0].size(): 0, layers = (min(m, n) + 1) / 2; | |
vector<int> res; | |
for(int k = 0; k < layers; ++k) | |
{ | |
for(int j = k; j < n - k; ++j) | |
res.push_back(matrix[k][j]); | |
for(int i = k + 1; i < m - k - 1; ++i) | |
res.push_back(matrix[i][n - k - 1]); | |
for(int j = n - k - 1; j >= k; --j) | |
if(m - k - 1 != k) | |
res.push_back(matrix[m - k - 1][j]); | |
for(int i = m - k - 2; i >= k + 1; --i) | |
if(n - k - 1 != k) | |
res.push_back(matrix[i][k]); | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment