赞
踩
思路:模拟,初始化上下左右4个方向的边界,逐步收缩,注意要及时判断元素是否已经放满,否则会放入多余元素
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int row = matrix.size(); int col = matrix[0].size(); vector<int> ans; int k = 1; int left = 0; int right = col-1; int top = 0; int bottom = row-1; while(k <= row*col){ if(ans.size() == col * row) break; for(int i = left;i<=right;++i,++k) ans.push_back(matrix[top][i]); top++; if(ans.size() == col * row) break; for(int i = top;i<=bottom;++i,++k) ans.push_back(matrix[i][right]); right--; if(ans.size() == col * row) break; for(int i = right;i>=left;--i,++k) ans.push_back(matrix[bottom][i]); bottom--; if(ans.size() == col * row) break; for(int i = bottom;i>=top;--i,++k) ans.push_back(matrix[i][left]); left++; } return ans; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。