45. Jump Game II

来源:互联网 发布:闲鱼怎么实现淘宝介入 编辑:程序博客网 时间:2024/06/16 18:06

题目:
https://leetcode.com/problems/jump-game-ii/description/

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.

分析:假设总是可以到达最后一个结点。再求最少的跳数。从0开始,最多可跳2次(A[0]=2)到达A[1],然后A[1]最多可跳3次,最远可跳到A[4]即末尾。所以最少跳数为2次。

在上诉过程中,关注的有:1.当前一共跳了多少次;2.jump次,跳到的最远位置;3.下一点,最远可以跳到什么位置;

所以设置3个变量:jump 表示当前一共跳了多少次;jump次,跳到的最远位置;next 表示jump+1次,最远可以跳到什么位置(在目前可达范围内,潜在的可以跳到的最远位置);

因为要遍历整个数组,所以一定有一个变量i,表示当前所在的位置。

class Solution {    public int jump(int[] nums) {        if(nums==null || nums.length<=0){            return 0;        }        int jump = 0;        int cur =0;        int next = 0;        for(int i=0;i<nums.length;i++){            if(cur<i){//cur<i ;jump次,不能跳到i位置,所以还需要多跳1次或者几次;所以jump++;cur = next;                jump++;                cur = next;            }            //cur>=i;jump次,已经可以到达i位置了;            next = Math.max(next,i+nums[i]);            //在遍历数组的过程中,每次i++,都要更新next的值,next = Math.max(next,i+A[i]);        }        return jump;    }}
原创粉丝点击