题目:
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.
题意:
从起点跳跃,每次跳跃的最大步数为该位置的数组值,求最后跳到最后一个位置上所需的最少步数。
思路:
每次跳跃都选择跳最远,如果开始跳的位置超出之前得到的最大跳跃范围preSelect,步数加1。同时preSelect更新为当前得到的最大跳跃范围。
代码:
class Solution {
public:
int jump(vector<int>& nums) {
int len=nums.size();
int dis=0;
int cnt=0;
int preSelect=0;
for(int i=0;i<len;i++){
if(i>preSelect){
cnt++;
preSelect=dis;
}
dis=max(dis,nums[i]+i);
}
return cnt;
}
};
最小跳跃次数算法

本文介绍了一个算法问题,即如何从数组起始位置跳跃至末尾,每次跳跃的最大步数由当前位置的数组值决定,目标是最少跳跃次数到达终点。文章提供了一种解决方案,通过不断更新可达最远距离来确定最少的跳跃次数。
1168

被折叠的 条评论
为什么被折叠?



