我的第一个思路:
优点:
缺点:要特别考虑只剩一个元素的情况!
我的C++代码:
class Solution
{
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
int m = matrix.size();
int n = matrix[0].size();
vector<int> sp(m*n, 0); // m*n 个 0
int k = 0;
int left = 0;
int right = n-1 ;
int top = 0;
int bottom = m-1;
while(left <= right && top <= bottom)
{
int row = top;
int col = left;
if(left == right && top == bottom)
{
sp[k] = matrix[row][col]; // 防止遗漏, 仅仅一个中心的情况要特殊处理
return sp;
}
while(col < right)
{
sp[k++] = matrix[row][col++];
}
while(row < bottom)
{
sp[k++] = matrix[row++][col];
}
while(col > left and (top < bottom or col==right)) //只有一行的情况要特殊处理,防止重复保存而导致越界
{
sp[k++] = matrix[row][col--];
}
while(row > top and (left < right or row==bottom)) //只有一列的情况要特殊处理,防止重复保存而导致越界
{
sp[k++] = matrix[row--][col]; // 四季轮回,回到起点
}
left++;
right--;
top++;
bottom--; // 收缩一圈
}
return sp;
}
};
第二个思路:
缺点:
优点:无需考虑只剩一个元素的情况。
我的C++代码:
class Solution
{
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
int m = matrix.size();
int n = matrix[0].size();
vector<int> sp(m*n, 0); // m*n 个 0
int k = 0;
int left = 0;
int right = n-1 ;
int top = 0;
int bottom = m-1;
while(left <= right && top <= bottom)
{
int row = top;
int col = left;
while(col <= right)
{
sp[k++] = matrix[row][col++];
}
row++;
col--; //挪到下一个列循环的起点
while(row < bottom)
{
sp[k++] = matrix[row++][col];
}
while(top < bottom && col >= left) //只有一行的情况要特殊处理,防止重复保存而导致越界
{
sp[k++] = matrix[row][col--];
}
row--;
col++; //挪到下一个列循环的起点
while(left < right && row > top) //只有一列的情况要特殊处理,防止重复保存而导致越界
{
sp[k++] = matrix[row--][col]; // 四季轮回,回到起点
}
left++;
right--;
top++;
bottom--; // 收缩一圈
}
return sp;
}
};
本文分享自 Python可视化编程机器学习OpenCV 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!