LeetCode 1345. 跳跃游戏 IV

1345. 跳跃游戏 IV

Solution

思路:

看到题目后,发现转化为无向图就可以了。然后就以为没事了,发现大意了,因为重复的值可能有很多,导致图非常的稠密,最后会导致TLE,这里学习了可以去子图的方法,因为相等的值会在第一次进去子图时将其他的点都入队,不需要遍历其他点时再进入该子图,因此可以将该值去除,防止重复进入。

class Solution {
    public int minJumps(int[] arr) {
        Map<Integer, List<Integer>> sameValue = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            sameValue.putIfAbsent(arr[i], new ArrayList<Integer>());
            sameValue.get(arr[i]).add(i);
        }
        Set<Integer> visited = new HashSet<>();
        Queue<int[]> queue = new ArrayDeque<>();
        queue.offer(new int []{0, 0});
        visited.add(0);
        while (!queue.isEmpty()) {
            int [] d = queue.poll();
            int idx = d[0], step = d[1];
            if (idx == arr.length - 1) {
                return step;
            }
            step++;
            int v = arr[idx];
            if (sameValue.containsKey(v)) {
                for (int x: sameValue.get(v)) {
                    if (visited.add(x)) {
                        queue.offer(new int[]{x, step});
                    }
                }
                sameValue.remove(v);
            }
            if (idx + 1 < arr.length && visited.add(idx + 1)) {
                queue.offer(new int[]{idx + 1, step});
            }
            if (idx - 1 >= 0 && visited.add(idx - 1)) {
                queue.offer(new int[]{idx - 1, step});
            }
        }
        return -1;
    }
}
posted @ 2022-01-22 15:00  Frontierone  阅读(28)  评论(0编辑  收藏  举报