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;
    }
}

posted @   你也要来一颗长颈鹿吗  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示