Leetcode-54. Spiral Matrix
来源:互联网 发布:171网络虚拟电话号码 编辑:程序博客网 时间:2024/06/10 05:47
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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]
.
这题目没啥好说的。。一开始自己作死用两个表示横竖,发现一些边界条件处理真麻烦,引用别人代码算了,逻辑都是一样的。Your runtime beats 10.42% of java submissions.
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if (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) { // Traverse Right for (int j = colBegin; j <= colEnd; j ++) { res.add(matrix[rowBegin][j]); } rowBegin++; // Traverse Down for (int j = rowBegin; j <= rowEnd; j ++) { res.add(matrix[j][colEnd]); } colEnd--; if (rowBegin <= rowEnd) { // Traverse Left for (int j = colEnd; j >= colBegin; j --) { res.add(matrix[rowEnd][j]); } } rowEnd--; if (colBegin <= colEnd) { // Traver Up for (int j = rowEnd; j >= rowBegin; j --) { res.add(matrix[j][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
- URL详解 window.location的一系列方法
- luogu2007 魔方
- 51Nod-1686-第K大区间
- 9. Doctrine2
- 前端HTML<img>标签图像的属性和使用/图像img与背景background的区别
- Leetcode-54. Spiral Matrix
- 线段树
- mysql中的存储过程使用事物后如何正确得到影响行数
- 架构师分类————想成为什么。怎么成为。
- 字符 java中String、StringBuffer、StringBuilder的区别
- perl一些转载
- 字符 谈谈字符集编码及gb2312、utf-8编码原理
- DFA
- JAVA中如何使用boolean的Demo