45. Jump Game II

Description

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.

Solution

Greedy, time O(n), space O(1)

用DP的话time O(n ^ 2)会TLE,必须采用跟"Jump Game"类似的Greedy思路将时间复杂度降下来。

考虑:到底什么时候总步数+1呢?
假设到遍历到数组i的位置,在此之前jump到的位置为k;在位置k最远可以到达的范围是[k,reach]。
那么如果i > reach,说明[k ~ reach]之间必须再jump一次,这样才能保证i在可以reach的范围内!所以此时++step。

考虑:那究竟在[k-reach]的哪个位置再次jump呢?
根据贪心算法,应该挑可以reach范围最远的那个点,如果需要求jump game的最短次数的jump路径,就需要记录这个点了。

class Solution {
    public int jump(int[] nums) {
        int lastReach = 0;
        int reach = nums[0];
        int steps = 0;
        
        for (int i = 1; i <= Math.min(reach, nums.length - 1); ++i) {
            if (i > lastReach) {
                ++steps;
                lastReach = reach;
            }
            reach = Math.max(i + nums[i], reach);
        }
        
        if (reach < nums.length - 1) {
            return -1;
        }
        
        return steps;
    }
}

你可能感兴趣的:(45. Jump Game II)