54-Spiral Matrix
来源:互联网 发布:java关键字有多少个 编辑:程序博客网 时间:2024/05/21 04:20
题目
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].
分析
顺时针、螺旋输出二维矩阵。 这道题是参考的得票最高的Solution。
思路清晰,非常值得学习!!!
比较重要的四个变量rowBegin,rowEnd,colBegin,colEnd
每输出一行数据,更新一下rowBegin 或者rowEnd
每输出一列数据,更新一下colBegin或者colEnd
实现
/*Author: FancyDate:2017-03-15Algorithm:54-SpiralMatrixTime Complexity: O(m*n)*/class Solution {public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> result; if (matrix.empty() || matrix.size() == 0 || matrix[0].size() == 0) return result; int rows = matrix.size(), cols = matrix[0].size(); //保存起始位置 int rowBegin = 0, colBegin = 0; int rowEnd = rows - 1, colEnd = cols - 1; while (rowBegin <= rowEnd&&colBegin <= colEnd) { for (int i = colBegin; i <= colEnd; i++) result.push_back(matrix[rowBegin][i]); rowBegin++; for (int i = rowBegin; i <= rowEnd; i++) result.push_back(matrix[i][colEnd]); colEnd--; if(rowBegin<= rowEnd) for (int i = colEnd; i >= colBegin; i--) result.push_back(matrix[rowEnd][i]); rowEnd--; if(colBegin<=colEnd) for (int i = rowEnd; i >= rowBegin; i--) result.push_back(matrix[i][colBegin]); colBegin++; } return result; }};
阅读全文
0 0
- [leetcode 54] Spiral Matrix
- [LeetCode 54]Spiral Matrix
- Spiral Matrix - LeetCode 54
- leetcode 54 : Spiral Matrix
- Leetcode #54 Spiral Matrix
- 54Spiral Matrix
- Leetcode#54||Spiral Matrix
- [54]Spiral Matrix
- LeetCode_OJ【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
- HBase笔记-3.shell
- [MoonML]-朴素贝叶斯分类器
- GitLab版本管理
- Java 和微服务
- 判断值为空
- 54-Spiral Matrix
- 修改oracle 10g的字符集
- PhoneGap || Cordova 安装以及导入AndroidStudio 遇到的问题
- Filter和Servlet的区别
- 55-Jump Game
- Java之FileChannel类的理解和使用
- MyBatis常用对象SqlSessionFactory和SqlSession介绍和运用
- mysql数据库优化--(3)设计 范式 Normal Format, 规范的格式
- 56-Merge Intervals && 57-Insert Interval