[算法][LeetCode]Spiral Matrix——螺旋矩阵
2024-09-22 05:26: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]
.
分析
举个例子自己从头到尾把数字列出来,很容易就找到规律了:
假设一维数组的坐标为x,取值范围是xMin~xMax;二维数组的坐标为y,取值范围是yMin~yMax。(也就是数组表示为int[y][x])
1. 从左到右,y=yMin,x: xMin->xMax,yMin++
2. 从上到下,x=xMax,y: yMin->yMax,xMax--
3. 从右到左,y=yMax,x: xMax->xMin,yMax--
4. 从下到上,x=xMin,y: yMax->uMin,xMin++
结束条件,xMin==xMax或者yMin==yMax
还要要注意的地方:空数组的情况要处理。
Java代码
public static ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> order = new ArrayList<Integer>();
if (matrix.length == 0 || matrix[0].length == 0) return order; int xMin = 0;
int yMin = 0;
int xMax = matrix[0].length - 1;
int yMax = matrix.length - 1; order.add(matrix[0][0]); int i = 0, j = 0;
while (true) {
while (i < xMax) order.add(matrix[j][++i]);
if (++yMin > yMax) break; while (j < yMax) order.add(matrix[++j][i]);
if (xMin > --xMax) break; while (i > xMin) order.add(matrix[j][--i]);
if (yMin > --yMax) break; while (j > yMin) order.add(matrix[--j][i]);
if (++xMin > xMax) break;
}
return order;
}
最新文章
- Yii的学习(5)--Active Record的关联
- Hadoop阅读笔记(三)——深入MapReduce排序和单表连接
- 谈谈Delph中的类和对象2---类可以理解成一种特殊的数据结构、类型转换
- GTD一些问题
- 2016年10月18日 星期二 --出埃及记 Exodus 19:2
- wireshark: there are no interfaces on which a capture can be done
- Oracle- 备份单表结构和单表数据
- Django db relationship
- web前端面试试题总结---其他
- java开发第一天
- mysql 数据库 切表的脚本
- linux apache 打模块示例
- tablelayoutpanel内部组件变形
- tensorflow Sigmoid 应用
- 美团小程序框架mpvue入门
- flask请求异步执行(转载)
- 2018秋寒假作业4—PTA编程总结1
- GO流程控制
- git flow分支管理
- DXP 内电层分割
热门文章
- 停掉一台服务器,Nginx响应慢(转载)
- appium 1.6.3 + ios 10.2 + xcode 8.2.1 真机运行iphone app
- django abstract base class ---- 抽象基类
- unity, Root Motion
- Android批量图片载入经典系列——afinal框架实现图片的异步缓存载入
- iOS_5_汤姆猫
- Out of Hay(poj2395)(并查集)
- CSS3背景总结
- python 加密方法总结
- STM32F10x_硬件I2C主从通信(轮询发送,中断接收)