LeetCode:Jump Game II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/alading2009/article/details/72597945

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 class Solution {
    public int jump(int[] nums) {
        int minJumpNum = 0;
        int index = 0;
        while (index < nums.length - 1) {
            index = nextIndex(nums, index);
            minJumpNum++;
        }
        return minJumpNum;
    }

    public int nextIndex(int[] nums, int start) {
        int len = nums[start], max = -len;
        if (len >= nums.length - start - 1) {
            return nums.length - 1;
        }
        int nextIndex = start + 1;
        for (int i = 1; i <= len && start + i < nums.length; i++) {
            int nextJumpLen = nums[start + i] - (len - i);
            if (nextJumpLen > max) {
                max = nextJumpLen;
                nextIndex = start + i;
            }
        }
        return nextIndex;
    }
}

猜你喜欢

转载自blog.csdn.net/alading2009/article/details/72597945