一、 跳跃游戏
1. 题目描述
给你一个非负整数数组 nums ,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
2. 代码展示
/*class Solution {
public int jump(int[] nums) {
//这题是贪心算法的典型,不能使用动态规划求解
//此方法时间复杂度很高!!
//这里采用的是从后往前找,因为要求步数最少,那么就需要你首先找到可以到达最后的位置的最远的地方,然后再往前找,还是找最远的地方
int position=nums.length-1;
int steps=0;
while(position>0){
for(int i=0;i<position;i++){
//找寻离最后的地方最远的位置i
if(i+nums[i]>=position){
position=i;
steps++;
break;
}
}
}
return steps;
}
}*/
class Solution{
public int jump(int[] nums) {
//方法二:从后往前这样找虽然可以找到我们想要的结果,但是终究还是时间复杂度很高,其实还有一种方法,就是从前往后找,每次都找到一个节点的未来允许跳跃范围内的最大跳跃的位置
int position=nums.length-1;
int end=0;
int steps=0;
int maxNums=0;
for(int i=0;i<position;i++){
maxNums=Math.max(maxNums,i+nums[i]);
if(i==end){
end=maxNums; //把条件更新为当前可以到达的最大位置
steps++;
}
}
return steps;
}
}