题意:
给一个二维数组,按螺旋顺序将其放入一个一维数组里。
举例:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
思路:
考察逻辑能力,纯粹的找规律,先自左向右取最上面一行,再自上而下取最右,自右向左取最下,自下而上取最左。每次都先检查释放已经取完。
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0)
return vector<int>();
int bot = matrix.size() - 1, right = matrix[0].size() - 1, top = 0, left = 0;
int rowNum = matrix.size(), colNum = matrix[0].size();
vector<int> res;
while (res.size() < rowNum*colNum) {
for (int col = left; col <= right; ++col)
res.push_back(matrix[top][col]);
top++;
if (res.size() < rowNum*colNum) {
for (int row = top; row <= bot; ++row)
res.push_back(matrix[row][right]);
right--;
}
if (res.size() < rowNum*colNum) {
for (int col = right; col >= left; --col)
res.push_back(matrix[bot][col]);
bot--;
}
if (res.size() < rowNum*colNum) {
for (int row = bot; row >= top; --row)
res.push_back(matrix[row][left]);
left++;
}
}
return res;
}