Leetcode 54. Spiral Matrix
来源:互联网 发布:淘宝宠物狗 编辑:程序博客网 时间:2024/06/15 03:59
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
class Solution {public: vector<int> spiralOrder(vector<vector<int>>& matrix) { if (matrix.size() == 0) return vector<int>(); int top = 0; int bottom = matrix.size() - 1; int left = 0; int right = matrix[0].size() - 1; vector<int> ret; while (left <= right) { for (int i = left; i <= right; ++i) { ret.push_back(matrix[top][i]); } ++top; if (top > bottom) break; for (int i = top; i <= bottom; ++i){ ret.push_back(matrix[i][right]); } --right; if (left > right) break; for (int i = right; i >= left; --i) { ret.push_back(matrix[bottom][i]); } --bottom; if (bottom < top) break; for (int i = bottom; i >= top; --i) { ret.push_back(matrix[i][left]); } ++left; } return ret; }};
略优化
class Solution {public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int nrows = matrix.size(); if (nrows == 0) return vector<int>(); int ncols = matrix[0].size(); // setp long; int top = 0; int bottom = 0; int left = 0; int right = 0; vector<int> ret; while (left + right < ncols) { copy(matrix[top].begin() + left, matrix[top].end() - right , back_inserter(ret)); ++top; if (top + bottom == nrows) break; for (int i = top; i != nrows - bottom; ++i){ ret.push_back(matrix[i][ncols - 1 - right]); } ++right; if (left + right == ncols) break; copy(matrix[nrows - 1 - bottom].rbegin() + right, matrix[nrows - 1- bottom].rend() - left, back_inserter(ret)); ++bottom; if (bottom + top == nrows) break; for (int i = nrows - 1 - bottom; i >= top; --i) { ret.push_back(matrix[i][left]); } ++left; } return ret; }};
阅读全文
0 0
- LeetCode 54. Spiral Matrix
- [LeetCode]54.Spiral Matrix
- LeetCode --- 54. Spiral Matrix
- [Leetcode] 54. Spiral Matrix
- [leetcode] 54.Spiral Matrix
- Leetcode-54.Spiral Matrix
- **LeetCode 54. Spiral Matrix
- Leetcode 54. Spiral Matrix
- [leetcode] 54. Spiral Matrix
- leetcode 54. Spiral Matrix
- 54. Spiral Matrix LeetCode
- leetcode 54. Spiral Matrix
- LeetCode *** 54. Spiral Matrix
- [LeetCode]54. Spiral Matrix
- LeetCode 54. Spiral Matrix
- LeetCode--54. Spiral Matrix
- LeetCode - 54. Spiral Matrix
- [Leetcode]54. Spiral Matrix
- MVP的简单登录
- php发送email
- VMware Tools安装教程
- 11 1&&11 2总结
- TypeScript快餐教程 (1)
- Leetcode 54. Spiral Matrix
- 移动通信制式常识
- 电影热搜API及微信菜单自定义开发
- Android解决使用广播监听网络状态变化时接收到多个广播的问题
- Worley Noise (三)
- fousrce
- 207. Course Schedule
- FTP上传下载删除
- 实验楼 Linux 基础入门 用户及文件权限管理 作业笔记