] [LeetCode spiral 54. Spiral Matrix matrix (Medium) (JAVA)

] [LeetCode spiral 54. Spiral Matrix matrix (Medium) (JAVA)

Topic Address: https://leetcode.com/problems/spiral-matrix/

Subject description:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Subject to the effect

Given a matrix of mxn elements (m row, n-column), follow a helical clockwise order, returns all the elements in the matrix.

Problem-solving approach

1, each cycle comprising a four-part, a lower right upper left
2, boundary cases special treatment

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if (matrix.length == 0 || matrix[0].length == 0) return res;
        int len = Math.min(matrix.length, matrix[0].length);
        for (int i = 0; i <= (len % 2 == 0 ? len / 2 - 1 : len / 2); i++) {
            for (int j = i; j < matrix[0].length - i; j++) {
                res.add(matrix[i][j]);
            }

            for (int j = i + 1; j < matrix.length - i; j++) {
                res.add(matrix[j][matrix[0].length - 1 - i]);
            }

            for (int j = matrix[0].length - 1 - i - 1; j >= i && i < len / 2; j--) {
                res.add(matrix[matrix.length - 1 - i][j]);
            }

            for (int j = matrix.length - 1 - i - 1; j > i && i < len / 2; j--) {
                res.add(matrix[j][i]);
            }
        }
        return res;
    }
}

When execution: 0 ms, defeated 100.00% of all users to submit in Java
memory consumption: 38.2 MB, beat the 5.23% of all users to submit in Java

Published 81 original articles · won praise 6 · views 2290

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/104776975