[leetcode] 45. Jump Game II (java)

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.

Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: 
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.

Note:
You can assume that you can always reach the last index.

难度:hard

题意:给一个非负整数的数组,从第0个位置出发,每个位置上的数字代表可以跳的最远距离,求到达最后一个位置的最少跳数。

思路:
局部贪心。当跳到的下一个位置出发可以达到的位置最远,则跳到该下一位置。
如2 3 1 1 4
当下一跳跳最远距离不会直接超过最后一个位置时:
从index=0出发,当跳距离为1时,index[0+1] = 3,可以达到的最远距离为index=4
从index=0出发,当跳距离为2时,index[0+2] = 1,可以达到的最远距离为index=3
故index=0时选择下一跳的距离为1,index变为1
从index=1出发,因为下一跳跳最远距离3时直接到了最后一个位置,故结束。

//局部贪心
class Solution {
    public int jump(int[] nums) {
        if(nums == null || nums.length == 0 || nums[0] == 0) return 0;
        if(nums.length == 2) return 1;
        int now = 0;
        int jump = 0;
        while(now < nums.length-1){
            int next = now;
            int farest = now;    
            for(int i = 1; i <= nums[now]; i++){
                if(now + nums[now] >= nums.length-1){
                    return ++jump;
                }
                if(now + i + nums[now+i] > farest){
                    farest = now + i + nums[now+i];
                    next = now + i;
                }
            }
            now = next;
            jump++;
        }
        return jump;
    }
}

上一篇:【牛客网-剑指offer】跳台阶


下一篇:在windows主机中,利用XSHELL生成“密钥”进行虚拟机与物理机的传输