Leetcode 54. Spiral Matrix
来源:互联网 发布:nginx tomcat 502 编辑:程序博客网 时间:2024/05/18 01:28
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]
.
注意 corner cases
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); if (matrix == null || matrix.length == 0) {return res;} int rowBegin = 0; int rowEnd = matrix.length - 1; int colBegin = 0; int colEnd = matrix[0].length - 1; while (rowBegin <= rowEnd && colBegin <= colEnd) { // right for (int i = colBegin; i <= colEnd; i++) { res.add(matrix[rowBegin][i]); } rowBegin++; // down for (int i = rowBegin; i <= rowEnd; i++) { res.add(matrix[i][colEnd]); } colEnd--; // left if (rowBegin <= rowEnd) { for (int i = colEnd; i >= colBegin; i--) { res.add(matrix[rowEnd][i]); } } rowEnd--; // up if (colBegin <= colEnd) { for (int i = rowEnd; i >= rowBegin; i--) { res.add(matrix[i][colBegin]); } } colBegin++; } return res; }
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
- 应用多级缓存模式支撑海量读服务
- android 使用selector设置背景
- (UVA)401
- string替换所有指定字符串(C++)
- Android 内存相关 onTrimMemory,onLowMemory,MemoryInfo()
- Leetcode 54. Spiral Matrix
- java多态之方法调用
- 「征文」我和极光有个约会
- MessageBox 单线程同步问题
- Linux 终端 terminal
- 《马云为什么错了?》
- 虚析构函数的作用和用法
- 微信小程序的发布配置及SSL证书配置
- 行为型设计模式-中介者模式