Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
spiral-matrix.cpp 2.48 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2015-11-28 15:26 +08:00 . Update spiral-matrix.cpp
// Time: O(m * n)
// Space: O(1)
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) {
return res;
}
for (int left = 0, right = matrix[0].size() - 1,
top = 0, bottom = matrix.size() - 1;
left <= right && top <= bottom;
++left, --right, ++top, --bottom) {
for (int j = left; j <= right; ++j) {
res.emplace_back(matrix[top][j]);
}
for (int i = top + 1; i < bottom; ++i) {
res.emplace_back(matrix[i][right]);
}
for (int j = right; top < bottom && j >= left; --j) {
res.emplace_back(matrix[bottom][j]);
}
for (int i = bottom - 1; left < right && i > top; --i) {
res.emplace_back(matrix[i][left]);
}
}
return res;
}
};
// Time: O(m * n)
// Space: O(1)
class Solution2 {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
const int m = matrix.size();
vector<int> res;
if (m == 0) {
return res;
}
const int n = matrix.front().size();
enum Action {RIGHT, DOWN, LEFT, UP};
Action action = RIGHT;
for (int i = 0, j = 0, begini = 0, beginj = 0, endi = m,
endj = n, cnt = 0, total = m * n; cnt < total; ++cnt) {
res.emplace_back(matrix[i][j]);
switch (action) {
case RIGHT:
if (j + 1 < endj) {
++j;
} else {
action = DOWN, ++begini, ++i;
}
break;
case DOWN:
if (i + 1 < endi) {
++i;
} else {
action = LEFT, --endj, --j;
}
break;
case LEFT:
if (j - 1 >= beginj) {
--j;
} else {
action = UP, --endi, --i;
}
break;
case UP:
if (i - 1 >= begini) {
--i;
} else {
action = RIGHT, ++beginj, ++j;
}
break;
default:
break;
}
}
return res;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助