[LeetCode]--54. Spiral Matrix
来源:互联网 发布:彻地钉db数据 编辑:程序博客网 时间:2024/06/06 20:38
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].
我想着把这个二维数组分成一层一层的环,然后一层一层的遍历,就能得到,而遍历环就是上边右边下边左边。就是要控制好循环结束之类的。
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if (matrix == null || matrix.length == 0) return res; int size = matrix.length * matrix[0].length; int len = Math.min(matrix.length, matrix[0].length); for (int i = 0; i < len; i++) { if (res.size() == size) break; visitCircle(res, matrix, i); } return res; } public void visitCircle(List<Integer> list, int[][] a, int m) { int len = a[0].length, hlen = a.length; for (int i = m; i < len - m; i++) { list.add(a[m][i]); } for (int i = 1 + m; i < hlen - m; i++) { list.add(a[i][len - m - 1]); } if (hlen - 2 * m == 1 || len - 2 * m == 1) return; for (int i = len - 2 - m; i >= m; i--) { list.add(a[hlen - m - 1][i]); } for (int i = hlen - m - 2; i > m; i--) { list.add(a[i][m]); } }
还有一种方法,跟我这个其实是一个意思,但是他没有这样表达。
public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> rst = new ArrayList<Integer>(); if (matrix == null || matrix.length == 0) return rst; int rows = matrix.length; int cols = matrix[0].length; int count = 0; while (count * 2 < rows && count * 2 < cols) { for (int i = count; i < cols - count; i++) rst.add(matrix[count][i]); for (int i = count + 1; i < rows - count; i++) rst.add(matrix[i][cols - count - 1]); if (rows - 2 * count == 1 || cols - 2 * count == 1) // if only one row /col remains break; for (int i = cols - count - 2; i >= count; i--) rst.add(matrix[rows - count - 1][i]); for (int i = rows - count - 2; i >= count + 1; i--) rst.add(matrix[i][count]); count++; } return rst; }
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下RecyclerView下拉刷新上拉加载Demo
- iOS多语言本地化(国际化)设置
- sklearn.model_selection的StratifiedKFold实例
- 排序——规则
- git add -A和 git add . git add -u区别
- [LeetCode]--54. Spiral Matrix
- 生活多快乐:笑死爹的程序段子
- hdu 4500 (小Q系列故事——屌丝的逆袭)
- 【css】你了解word-wrap和word-break的区别吗?
- php高并发秒杀解决方案
- HttpClient 在Java项目中的使用详解
- 单机版solr6.2.1搭建window
- swift 元组 数组 字典 简单方法实现 小结
- linux 时间同步的方法