给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
[2,3,1,1,4]
从第一个位置开始走,最多走max步,在这max布的区间(也就是例子中的 【2,3,1】)寻找当前位置 i 加上能走的最大步总和的最大值,也就是能走的最远方向,以此类推,直到总和最大值大于等于最后的位置。
class Solution {
public int jump(int[] nums) {
int start = 0;
int max ;
int i = start;
int step = 0;
while( start<nums.length){
max = start + nums[start];
if(max>=nums.length-1){
step+=1;
break;
}
int max_t = max;
for(i = start; i<=max_t;i++){
if(i + nums[i]>max){
max = i + nums[i];
start = i;
}
}
step+=1;
}
return step;
}
}
上面代码也是用到贪心算法,在当前位置能走的最大的位置之间,寻找下一个位置,使其能走的位置比当前位置更远。