最小跳跃数

xiaoxiao2021-02-28  32

       给定一个非负整数数组,初始情况位于数组的第一个索引处。数组中的每个元素表示该位置的最大跳跃长度。要求达到最后一个索引花费的最小跳跃次数。

<举例>

输入: [2,3,1,1,4] 输出: 2

解释: 跳到最后一个索引的最小跳数为2。从索引0跳到1跳1步,然后跳3步到最后一个索引。

public static int canJump(int[] a) { int cur=0,far=0,step=0; far=a[0]; while(cur<a.length){ if(far>=a.length-1) return step+1; int nextstep=cur,temp=far; while(cur<=temp){ if(a[cur]+cur>far){ nextstep=cur; far=a[cur]+cur; } cur++; } step++; cur=nextstep; } return -1; }
转载请注明原文地址: https://www.6miu.com/read-2612618.html

最新回复(0)