45. Jump Game II

来源:互联网 发布:故宫软件 编辑:程序博客网 时间:2024/05/19 10:35

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.)

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

动态规划题,可以通过滑动窗口的方法求解,程序如下所示:

class Solution {    public int jump(int[] nums) {        if (nums.length == 1){            return 0;        }        int left = 0, right = 0;        int num = 0, maxIndex = 0;        while (true){            num ++;            for (int i = left + 1; i < right; ++ i){                int tmp = i + nums[i];                if (maxIndex <= tmp){                    maxIndex = tmp;                }            }            maxIndex = Math.max(right + nums[right], maxIndex);            if (maxIndex >= nums.length - 1){                return num;            }            left = right;            right = maxIndex;        }    }}