] [Matriz 54. espiral Matrix LeetCode espiral (Medium) (JAVA)

] [Matriz 54. espiral Matrix LeetCode espiral (Medium) (JAVA)

Tema Dirección: https://leetcode.com/problems/spiral-matrix/

Descripción Asunto:

Dada una matriz de elementos de mxn (m filas, n columnas), devolver todos los elementos de la matriz con el fin de espiral.

Ejemplo 1:

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

Ejemplo 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]

Sujeto al efecto

Dada una matriz de elementos de mxn (m fila, n-columna), seguir un orden en sentido horario helicoidal, declaraciones de todos los elementos en la matriz.

Enfoque de resolución de problemas

1, comprendiendo cada ciclo una de cuatro partes, una parte inferior izquierda superior derecha
2, los casos de contorno tratamiento especial

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

Cuando la ejecución: 0 ms, derrotado 100.00% de todos los usuarios a presentar en Java
consumo de memoria: 38,2 MB, batir el 5,23% de todos los usuarios a presentar en Java

Publicado 81 artículos originales · ganado elogios 6 · vistas 2290

Supongo que te gusta

Origin blog.csdn.net/qq_16927853/article/details/104776975
Recomendado
Clasificación