【题目】:54. 螺旋矩阵
class Solution {
public:vector<int> spiralOrder(vector<vector<int>>& matrix) {int startx = 0, starty = 0; // 起始坐标vector<int> res;int m = matrix.size(), n = matrix[0].size();int count = min(m, n) / 2;int i, j;int offset = 1;// 填充边缘while(count--) {// 向右for(j = startx; j < n - offset; ++j) {res.push_back(matrix[startx][j]);}// 向下for(i = starty; i < m - offset; ++i) {res.push_back(matrix[i][j]);}// 向左for(; j > starty; --j) {res.push_back(matrix[i][j]);}// 向上for(; i > startx; --i) {res.push_back(matrix[i][j]);}++offset;++startx;++starty;}// 考虑只剩一行的情况if(m <= n && m % 2 == 1) {for(; starty <= n - offset; ++starty) {res.push_back(matrix[startx][starty]);}}// 考虑只剩一列的情况if(n < m && n % 2 == 1) {for(; startx <= m - offset; ++startx) {res.push_back(matrix[startx][starty]);}}return res;}
};
- 时间复杂度: O(n)
- 空间复杂度: O(1)
这题主要是要抓住循环不变量,每次一圈循环都应该遵循左闭右开的原则。
由于题目不一定是个正方形,所以最后要考虑只剩一行
或只剩一列
的情况