leetcode-54. Spiral Matrix
来源:互联网 发布:淘宝店铺宝贝不见了 编辑:程序博客网 时间:2024/06/05 11:08
leetcode-54. Spiral Matrix
题目:
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].
这题的思路就是如果顺时针转的话。那么每次我们连续向list中添加几个数。例如是3*3的格子,只要依次添加3,2,2,1,1就行,这里就有一定的规律了。每次添加matrix,length–或者matrix[0].length–的个数就好。那剩下的就是编程实现的问题了。虽然比较麻烦,但是基本上思路试很清晰的。
另外一个小问题是计数。我这里没有想到什么好的办法,就是求出总的数组数字数量。然后计数直到计数到数组数字数量为止。
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> ret= new ArrayList<Integer>(); if(matrix==null || matrix.length==0 || matrix[0].length==0) return ret; int m = matrix[0].length, n=matrix.length,total=m*n,i=0,j=-1,c=0; n--; boolean row=false,col=false; while(c<total){ for(int t = 0;t < m;t++){ if(row) j--; else j++; // System.out.println(i+" "+j); ret.add(matrix[i][j]); c++; } m--; row=!row; if(c>=total) break; for(int t = 0;t < n;t++){ if(col) i--; else i++; // System.out.println(i+" "+j); ret.add(matrix[i][j]); c++; } n--; col=!col; } 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
- Oracle 10g安装配置
- 双显卡笔记本在Ubuntu下使用cuda的解决方案(转)
- 设置Activity全屏的几种方式
- docker gitlab碰到的一些问题
- armeabi 、armeabi-v7a 和x86
- leetcode-54. Spiral Matrix
- SQL Server 常用系统表(三) systypes
- laravel笔记路由组群
- MyBatis批量的增删改查操作
- MongoDB配置文件说明
- opencv+ linux + cmake 生成 opencv静态库
- 二分查找和顺序查找
- DeployMaster5.0.1汉化版下载-文件生成器
- ID_Card