Implementação Java de leetcode54, 59, 61 questões
54. Matriz Espiral
Descrição do título
Dada uma matriz contendo mxn elementos (m linhas, n colunas), siga a ordem em espiral no sentido horário para retornar todos os elementos na matriz.
Exemplo 1:
Entrada:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Saída: [1,2,3,6,9,8,7,4,5 ]
Exemplo 2:
Entrada:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Saída: [1,2,3,4,8,12 , 11,10,9,5,6,7]
Ideias
Se você vai para a direita até o final, muda para o fundo, se você vai para o final, você muda para a esquerda, se você vai para o final, você muda para o topo, e se você vai para o final, você mude para a direita. Defina a matriz visitada para indicar se você visitou
Código
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return order;
}
int rows = matrix.length, columns = matrix[0].length;
boolean[][] visited = new boolean[rows][columns];
int total = rows * columns;
int row = 0, column = 0;
int[][] directions = {
{
0, 1}, {
1, 0}, {
0, -1}, {
-1, 0}};
int directionIndex = 0;
for (int i = 0; i < total; i++) {
order.add(matrix[row][column]);
visited[row][column] = true;
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
directionIndex = (directionIndex + 1) % 4;
}
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
}
59. Spiral Matrix II
Descrição do título
Dado um número inteiro positivo n, gere uma matriz quadrada contendo todos os elementos de 1 a n2, e os elementos são dispostos em espiral no sentido horário.
Exemplo:
Entrada: 3
Saída:
[
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]
]
Ideias
Direita, baixo, esquerda e cima, deixe o limite mudar toda vez que você chegar ao limite, por exemplo, quando a linha termina bem no fundo, deixe o número de linhas ++
Código
class Solution {
public int[][] generateMatrix(int n) {
int l = 0, r = n - 1, t = 0, b = n - 1;
int[][] mat = new int[n][n];
int num = 1, tar = n * n;
while(num <= tar){
for(int i = l; i <= r; i++) mat[t][i] = num++; // left to right.
t++;
for(int i = t; i <= b; i++) mat[i][r] = num++; // top to bottom.
r--;
for(int i = r; i >= l; i--) mat[b][i] = num++; // right to left.
b--;
for(int i = b; i >= t; i--) mat[i][l] = num++; // bottom to top.
l++;
}
return mat;
}
}
61. Lista vinculada rotativa
Descrição do título
Dada uma lista encadeada, gire a lista encadeada e mova cada nó da lista encadeada k posições para a direita, onde k é um número não negativo.
Exemplo 1:
Entrada: 1-> 2-> 3-> 4-> 5-> NULL, k = 2
Saída: 4-> 5-> 1-> 2-> 3-> NULL
Explicação:
Gire para a direita 1 etapa: 5 -> 1-> 2-> 3-> 4-> NULL
Girar para a direita 2 etapas: 4-> 5-> 1-> 2-> 3-> NULL
Exemplo 2:
Entrada: 0-> 1-> 2-> NULL, k = 4
Saída: 2-> 0-> 1-> NULL
Explicação:
Gire uma etapa para a direita: 2-> 0-> 1-> NULL
direção Girar para a direita 2 etapas: 1-> 2-> 0-> NULL
Girar para a direita 3 etapas: 0-> 1-> 2-> NULL
Girar para a direita 4 etapas: 2-> 0-> 1-> NULL
Ideias
Primeiro conecte-se a uma lista ligada circular, em seguida, encontre o novo nó principal e, em seguida, envie
Código
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return null;
if (head.next == null) return head;
// 循环链表实现
ListNode old_tail = head;
int n;
for(n = 1; old_tail.next != null; n++)
old_tail = old_tail.next;
old_tail.next = head;
// 新的尾 : (n - k % n - 1)
// 新的头 : (n - k % n)
ListNode new_tail = head;
for (int i = 0; i < n - k % n - 1; i++)
new_tail = new_tail.next;
ListNode new_head = new_tail.next;
new_tail.next = null;
return new_head;
}
}