1. 程式人生 > >LeetCode:Jump Game II

LeetCode:Jump Game II

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; } }