• 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;
        }
    }
    
  • 相关阅读:
    试述软件的概念和特点?软件复用的含义?构件包括哪些?
    Spring Security基本用法
    java中跳出循环的方式
    cookie和session区别
    spring中类型注解下的bean的加载顺序
    常见的异常
    aop使用场景
    缓存类似于redis
    旧版redis使用
    获取rdis的几种方式
  • 原文地址:https://www.cnblogs.com/ACMerszl/p/15834024.html
Copyright © 2020-2023  润新知