[Leetcode学习-java]Jump Game IV

问题:

难度:hard

说明:

题目给出一个数组,从数组头开始,到数组末,返回最小需要多少步。

每一步只能操作:

1、往前一步 i + 1 < arr.length;

2、往后一步 i - 0 >= 0

3、跳到 arr[i] == arr[j] 的另外一个 j 位置

题目连接:https://leetcode.com/problems/jump-game-iv/

相关算法:

[Leetcode学习-java]Jump Game I~III :

https://blog.csdn.net/qq_28033719/article/details/110378502

输入范围:

  • 1 <= arr.length <= 5 * 10^4
  • -10^8 <= arr[i] <= 10^8

输入案例:

Example 1:
Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3
Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.

Example 2:
Input: arr = [7]
Output: 0
Explanation: Start index is the last index. You don't need to jump.

Example 3:
Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
Explanation: You can jump directly from index 0 to index 7 which is last index of the array.

Example 4:
Input: arr = [6,1,9]
Output: 2

Example 5:
Input: arr = [11,22,7,7,7,7,7,7,7,22,13]
Output: 3
 

我的代码:

其实这题达不到 hrad 难度,就用 bfs 就可以了,但我就是想不出来,想了个 全排列, dfs 然后居然想到了 dp 然后就自乱脚步了。

讲道理,JumpGame II 才是有深度的题,但是 II 只不过是 medium

Jump Game II :https://blog.csdn.net/qq_28033719/article/details/110378502

只需要用 bfs,把下一步所有可能的点都放入队列中,而且不能够是已经访问的点,此外上一步已经访问的点也不会在下一步存在,因为 bfs 就是有特点,同一阶的节点不会访问另一个节点,而且按照走的步数,也确实,当前所有可能的步数状态集不应该存在于下一个状态集。

class Solution {
    public int minJumps(int[] arr) {
        int len = arr.length, begin = 0, end = 1, count = 0;
        Map<Integer, List<Integer>> cache = new HashMap<>();
        for(int i = 0; i < len; i ++) {
            cache.putIfAbsent(arr[i], new ArrayList<Integer>());
            cache.get(arr[i]).add(i);
        }
        int[] queue = new int[len]; // 用队列 bfs
        boolean visited[] = new boolean[len]; // bfs 特征, 一个节点不会被其他同阶节点访问
        visited[0] = true;
        while(begin < end) {
            int e = end;
            for(;begin < e;begin ++) {
                int temp = queue[begin], bTemp = temp - 1, nTemp = temp + 1;
                if(temp == len - 1) return count;
                if(cache.containsKey(arr[temp])) // 添加了节点下一阶就移除
                    for(Integer index : cache.get(arr[temp])) 
                        if(!visited[index] && index != temp) {
                             queue[end ++] = index;
                            visited[index] = true;
                        }
                cache.remove(arr[temp]);
                if(bTemp > 0 && !visited[bTemp]) { // 加入 -1 节点
                    queue[end ++] = bTemp;
                    visited[bTemp] = true;
                }
                if(nTemp < len && !visited[nTemp]) { // 加入 +1 节点
                    queue[end ++] = nTemp;
                    visited[nTemp] = true;
                }
            }
            count ++;
        }
        return -1;
    } 
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/111849840