mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
添加 54.螺旋矩阵 Java 版本
This commit is contained in:
@ -133,5 +133,73 @@ public:
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
### Java
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public List<Integer> spiralOrder(int[][] matrix) {
|
||||
//存放数组的数
|
||||
List<Integer> ans = new ArrayList<>();
|
||||
//列数
|
||||
int columns = matrix[0].length;
|
||||
//行数
|
||||
int rows = matrix.length;
|
||||
//遍历起点
|
||||
int start = 0;
|
||||
//循环的次数 行数和列数中的最小值除以二
|
||||
int loop = Math.min(rows,columns) / 2;
|
||||
//未遍历的中间列(行)的列(行)下标
|
||||
int mid = loop;
|
||||
//终止条件
|
||||
int offSet = 1;
|
||||
int i,j;
|
||||
while(loop-- > 0) {
|
||||
//初始化起点
|
||||
i = j = start;
|
||||
|
||||
//从左往右
|
||||
for(; j < columns - offSet; j++)
|
||||
ans.add(matrix[i][j]);
|
||||
|
||||
//从上往下
|
||||
for(; i < rows - offSet; i++)
|
||||
ans.add(matrix[i][j]);
|
||||
|
||||
//从右往左
|
||||
for(; j > start; j--)
|
||||
ans.add(matrix[i][j]);
|
||||
|
||||
//从下往上
|
||||
for(; i > start; i--)
|
||||
ans.add(matrix[i][j]);
|
||||
|
||||
//每循环一次 改变起点位置
|
||||
start++;
|
||||
//终止条件改变
|
||||
offSet++;
|
||||
}
|
||||
|
||||
//如果行和列中的最小值是奇数 则会产生中间行或者中间列没有遍历
|
||||
if(Math.min(rows,columns) % 2 != 0) {
|
||||
//行大于列则产生中间列
|
||||
if(rows > columns) {
|
||||
//中间列的行的最大下标的下一位的下标为mid + rows - columns + 1
|
||||
for(int k = mid; k < mid + rows - columns + 1; k++) {
|
||||
ans.add(matrix[k][mid]);
|
||||
}
|
||||
}else {//列大于等于行则产生中间行
|
||||
//中间行的列的最大下标的下一位的下标为mid + columns - rows + 1
|
||||
for(int k = mid; k < mid + columns - rows + 1; k++) {
|
||||
ans.add(matrix[mid][k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user