Jump Game II

来源:互联网 发布:python 并行编程 编辑:程序博客网 时间:2024/06/08 14:26

原题:

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.

给定数组里每个元素的值表示从该元素位置最多能往后跳几个元素。返回调到数组末尾需要的最少步数。数组元素都是非负的。


思考过程:

一开始想的是递归遍历所有情况,找到步数最少的。后来看了别人的博客,深受启发:可以记录这一步能到达的最远位置和下一步能到达的最远位置,如果下一步最远能到数组末尾,那就返回步数。


解题思路:

就是一个不断记录、更新第n步能到达最远位置和第n + 1步能到达最远位置过程,n + 1步能到末尾就返回。详情见注释。


结果代码:

public int jump(int[] nums) {        int thisStepReach = nums[0],nextStepReach = nums[0],step = 1,len = nums.length;//分别记录此步最远能到达位置、下一步能到最远位置、步数。        if (len == 1) return 0;//如果数组只有一个元素,需要0步。        if (nums[0] >= len - 1) return 1;//如果第一步就可以到末尾,返回1。        for (int i = 1;i < len;i++){//遍历数组,从第二个元素开始。因为第一个元素在初始化时候已经处理了。            if (i > thisStepReach){//如果当前位置已经超过“这一步的最远位置”,那现在已经处于下一步了,所以步数增加,thisStepReach更新成以前的nextStepReach。                thisStepReach = nextStepReach;                step++;            }            nextStepReach = Math.max(nextStepReach,nums[i] + i);//每次都要更新下一步能到的最远位置。            if (nextStepReach >= len - 1) return step + 1;//如果下一步能到末尾,返回当前步数加一。        }        return 0;    }