LeetCode54 螺旋矩阵
题目
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
方法
模拟法
- 时间复杂度:O(mn),m为行数,n为列数
- 空间复杂度:O(mn)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
if(matrix==null||matrix.length==0||matrix[0].length==0){
return ans;
}
int rowLen = matrix.length , colLen = matrix[0].length;
int row = 0,col = 0,directionIndex = 0,total = rowLen*colLen;
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
boolean[][] visited = new boolean[rowLen][colLen];
for(int i=0;i<total;i++){
ans.add(matrix[row][col]);
visited[row][col] = true;
int nextRow = row+directions[directionIndex][0],nextCol = col+directions[directionIndex][1];
if(nextRow<0||nextRow>=rowLen||nextCol<0||nextCol>=colLen||visited[nextRow][nextCol]){
directionIndex = (directionIndex+1)%4;
}
row += directions[directionIndex][0];
col += directions[directionIndex][1];
}
return ans;
}
}
优化版模拟法
先计算出边界:left,right,top,bottom,然后在边界内遍历
- 时间复杂度:O(mn),m为行数,n为列数
- 空间复杂度:O(1)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
if(matrix==null||matrix.length==0||matrix[0].length==0){
return ans;
}
int rows = matrix.length,cols = matrix[0].length;
int left = 0, right = cols-1, top = 0, bottom = rows-1;
while (left<=right&&top<=bottom){
for(int i = left;i<=right;i++){ //往右
ans.add(matrix[left][i]);
}
for(int i = top+1;i<=bottom;i++){ //往下
ans.add(matrix[i][right]);
}
if(left<right&&top<bottom){ // 这个是确保两个条件同时满足,来滤除一行或一列的情况
for(int i = right-1;i>left;i--){ //往左
ans.add(matrix[bottom][i]);
}
for(int i = bottom;i>top;i--){ //往上
ans.add(matrix[i][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return ans;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了