阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给定一个整数数组 arr,你从下标 0 开始。每一步可以从下标 i 跳到:
i + 1(需满足 i + 1 < arr.length)i - 1(需满足 i - 1 >= 0)j(需满足 arr[j] == arr[i] 且 j != i)求到达数组最后一个下标的最少操作次数。
示例:
输入:
arr = [100,-23,-23,404,100,23,23,23,3,404]输出:3解释:最优路径:0 → 4 → 3 → 9,共3次跳跃。
输入:
arr = [7]输出:0解释:初始位置就是终点,无需跳跃。
i+1i-1package lc1345;
import java.util.*;
class Solution {
int bfs(HashMap<Integer, List<Integer>> map, int[] arr) {
int res = 0;
int last = arr.length - 1;
boolean[] visited = new boolean[arr.length];
Queue<Integer> queue = new LinkedList();
queue.offer(0);
while (!queue.isEmpty()) {
int m = queue.size();
for (int i = 0; i < m; i++) {
int n = queue.poll();
visited[n] = true;
if (n == last) {
return res;
}
if (n < last && !visited[n + 1]) {
visited[n + 1] = true;
queue.offer(n + 1);
}
if (n > 0 && !visited[n - 1]) {
visited[n - 1] = true;
queue.offer(n - 1);
}
if (map.containsKey(arr[n])) {
List<Integer> list = map.get(arr[n]);
for (int num : list) {
if (num != n && !visited[num]) {
visited[num] = true;
queue.offer(num);
}
}
map.remove(arr[n]);
}
}
res += 1;
}
return -1;
}
public int minJumps(int[] arr) {
HashMap<Integer, List<Integer>> map = new HashMap<>();
for (int i = arr.length - 1; i >= 0; i--) {
map.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
}
return bfs(map, arr);
}
}减少if分支判断,合并重复逻辑,使用更高效的队列实现:
package lc1345;
import java.util.*;
class Solution {
public int minJumps(int[] arr) {
int n = arr.length;
if (n == 1) return 0;
HashMap<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
}
boolean[] visited = new boolean[n];
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(0);
visited[0] = true;
int step = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int curr = queue.poll();
if (curr == n - 1) return step;
// 处理左右邻居
if (curr + 1 < n && !visited[curr + 1]) {
visited[curr + 1] = true;
queue.offer(curr + 1);
}
if (curr - 1 >= 0 && !visited[curr - 1]) {
visited[curr - 1] = true;
queue.offer(curr - 1);
}
// 处理同值下标
if (map.containsKey(arr[curr])) {
for (int next : map.get(arr[curr])) {
if (!visited[next]) {
visited[next] = true;
queue.offer(next);
}
}
map.remove(arr[curr]);
}
}
step++;
}
return -1;
}
}时间复杂度:
空间复杂度: