Leetcode -- Jump Game II

来源:互联网 发布:奔驰换大灯编程教程 编辑:程序博客网 时间:2024/06/07 20:37

https://oj.leetcode.com/problems/jump-game-ii/


Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

public int jump(int[] A)

问题分析:这题的解法就在于每次跳跃过程里,都选择下一步能够跳最远的那一格。第一步是没办法选的,必须是A[0],假设A[0]能够跳i步,那么在A[1]到A[i]之间,我们都维护下一步可能的最远距离,也就是A[k] + k ( 1 <= k <= i),然后到了第i格的时候,我们就跳最远的距离,然后步数加一。直到有一步能够跳到数组边界为止。难度不是很高,不知道为啥leetcode给了hard,给出代码如下:

    public int jump(int[] A) {        if(A.length <= 1)            return 0;        int step = 0;        int next_max =  A[0];        int cur_max = 0;        for(int i = 0; i < A.length; i++){            if(cur_max >= A.length - 1)                break;            next_max = Math.max(A[i] + i, next_max);            if(cur_max == i){                cur_max = next_max;                step++;            }        }        return step;    }


0 0
原创粉丝点击