1345. 跳跃游戏 IV
给你一个整数数组 arr ,你一开始在数组的第一个元素处(下标为 0)。
每一步,你可以从下标 i 跳到下标:
i + 1 满足:i + 1 < arr.length
i - 1 满足:i - 1 >= 0
j 满足:arr[i] == arr[j] 且 i != j
请你返回到达数组最后一个元素的下标处所需的 最少操作次数 。
注意:任何时候你都不能跳到数组外面。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-iv
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.*;
class Solution {
public int minJumps(int[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
Queue<Info> queue = new LinkedList<>();
Map<Integer, Set<Integer>> graph = new HashMap<>();
for (int i = 0; i < arr.length; ++i) {
graph.computeIfAbsent(arr[i], k -> new HashSet<>()).add(i);
}
graph.get(arr[0]).remove(0);
queue.offer(new Info(0, 0));
while (!queue.isEmpty()) {
Info node = queue.poll();
if (node.index == arr.length - 1) {
return node.step;
}
for (Integer to : graph.getOrDefault(arr[node.index], Collections.emptySet())) {
queue.offer(new Info(to, node.step + 1));
}
graph.remove(arr[node.index]);
if (node.index - 1 >= 0 && graph.containsKey(arr[node.index - 1])) {
graph.get(arr[node.index - 1]).remove(node.index - 1);
queue.offer(new Info(node.index - 1, node.step + 1));
}
if (node.index + 1 < arr.length && graph.containsKey(arr[node.index + 1])) {
graph.get(arr[node.index + 1]).remove(node.index + 1);
queue.offer(new Info(node.index + 1, node.step + 1));
}
}
return -1;
}
}
class Info {
int index;
int step;
public Info(int index, int step) {
this.index = index;
this.step = step;
}
}
心之所向,素履以往 生如逆旅,一苇以航
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】