0
点赞
收藏
分享

微信扫一扫

Day32 螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素

https://leetcode-cn.com/problems/spiral-matrix/

示例1:

示例2:

提示:

Java解法

package sj.shimmer.algorithm.m2;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SJ on 2021/2/25.
 */

class D32 {
    public static void main(String[] args) {
        System.out.println(spiralOrder(new int[][]{{2},{3}}));
        System.out.println(spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9},}));
        System.out.println(spiralOrder(new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}}));
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if (matrix != null) {
            int height = matrix.length;
            int width = matrix[0].length;
            int maxTurn = (Math.min(height, width)+1) / 2;
            for (int i = 0; i < maxTurn; i++) {
                int top = i;
                while (top < width - i) {
                    list.add(matrix[i][top]);
                    top++;
                }
                int right = i+1;
                while (right < height - i-1) {
                    list.add(matrix[right][width-i-1]);
                    right++;
                }
                if (i==height-1-i) {
                    continue;
                }
                int bottom = width-i-1;
                while (bottom >= i) {
                    list.add(matrix[height-i-1][bottom]);
                    bottom--;
                }
                if (i==width-i-1) {
                    continue;
                }
                int left = height-i-2;
                while (left > i) {
                    list.add(matrix[left][i]);
                    left--;
                }
            }
        }
        return list;
    }
}

官方解

https://leetcode-cn.com/problems/spiral-matrix/solution/luo-xuan-ju-zhen-by-leetcode-solution/

  1. 模拟

    • 时间复杂度:O(mn)
    • 空间复杂度:O(mn)
  2. 按层模拟

    • 时间复杂度:O(mn)
    • 空间复杂度:O(1)
举报

相关推荐

0 条评论