54Spiral Matrix
来源:互联网 发布:it安全管理 编辑:程序博客网 时间:2024/06/02 05:27
题目链接:https://leetcode.com/problems/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].
解题思路:
1、先确定二维数组包含几个圈
2、每一圈用四个 while 循环遍历(从左到右,从上到下,从右到左,从下到上 的)元素
3、第一个 while 循环是必须的;第三个 while 循环只有经过第二个 while 循环后才会执行,也就是说二维数组的行数必须大于 1 时,才会执行从右到左的扫描;第四个 while 循环必须经过第二和第三个 while 循环后才执行,即数组的行数和列数都必须大于 2 才执行从下到上的扫描。
注:《剑指Offer》上有类似的题目!!
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> list = new ArrayList(); if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return list; int row = matrix.length; int columns = matrix[0].length; if(row == 1 && columns == 1) { list.add(matrix[0][0]); return list; } int n = Math.min(row, columns); int circleNum; if(n % 2 == 0) circleNum = n / 2; else circleNum = n / 2 + 1; for(int k = 0 ; k < circleNum; k ++) { int i = k; int j = k; while(j < (columns - k)) { list.add(matrix[i][j]); j ++; } j --; i ++; while(i < row - k) { list.add(matrix[i][j]); i ++; } if(i != row - k) break; i --; j --; while(j >= k && i != k) { list.add(matrix[i][j]); j --; } if(j != k - 1) break; j ++; i --; while(i >= k + 1 && columns != 1) { list.add(matrix[i][j]); i --; } } return list; }}
21 / 21 test cases passed.Status: AcceptedRuntime: 276 ms
方法相似的题目:59 Spiral Matrix II
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
- 2016校招华为机试题——好友推荐
- 移动H5前端性能优化指南
- 九度 Online Judge 算法 刷题 题目1052:找x
- 时间段和数字之间的相互转换
- Python GUI编程(Tkinter)
- 54Spiral Matrix
- hdoj 4746 莫比乌斯反演 + 优化
- 黑马程序员——java复习总结——File类和其他流对象
- 一些Docker的技巧与秘诀
- Python使用wxPython、py2exe编写桌面程序
- hive创建表时加了中文备注comment报错
- ubuntu设置系统时间与网络时间同步
- perl practice
- windows中安装vm workstation,如何配置网卡信息避免windows和虚拟机来回切换