-
问题介绍:
- 问题描述:
- 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.
- 示例:
- Input: [2,3,1,1,4]
- Output: 2
- Explanation: 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.
- 问题描述:
-
解决思路:
- 解法一:
- 思路:首先想到的是用递归把所有能够到达最后一个元素的跳法全部找出来,保存跳转的次数到一个数组中,最后对数组进行排序,输出最小的值即为问题所求值。在输入的数组较小的时候,能够符合解法的时间限制,当输入数组过大的时候,就会超时;
- 代码:
- 解法一:
class Solution {
public:
int jump(vector<int>& nums) {
int index=0;
int count=0;
vector<int> resp;
proc(nums,index,count,resp);
sort(resp.begin(),resp.end());
return resp[0];
}
void proc(vector<int>& nums,int index,int count,vector<int> &resp)
{
if(index==nums.size()-1)
{
resp.push_back(count);
}
else if(index>=nums.size())
{
return;
}
else
{
for(int i=1;i<=nums[index];i++)
{
count++;
index+=i;
proc(nums,index,count,resp);
index-=i;
count--;
}
}
}
};
- 解法二:网上学习到别人时间复杂度为O(n)的解法;
- 思路:
- 利用贪心算法,遍历数组,**每次取前一次跳跃后其跳跃范围中所有元素能够跳到最远范围的那一个元素作为下一跳目标;**而不是每次取最远跳的元素,因为所有的局部最优并不一定等于全局最优;
- 在实现的过程中,遍历数组的时候设置两个标志位last和cur,last记录了上一次跳跃能够达到的最远位置,cur记录了当前遍历到的元素能够跳跃的最远位置和前面已遍历元素能够跳跃的最远位置的最大值;假设当前遍历到元素i,且i<=last,则表示现在的遍历仍然在上一跳的范围中,此时算法的目标就是要在所有包含在上一跳的范围中的元素中寻找能够跳到的最远的位置,用cur=max(cur,i+nums[i])来记录;当i>last的时候,就表示此时已经跳出了上一跳的范围,这时候跳跃次数需要+1,且last需要更新为cur,而新的cur则需要在i到更新后的last中去寻找;按照这样的顺序,当cur包含了数组的最后一个元素的时候,此时记录的跳跃次数即为最后要求的值了;
- 代码:
- 思路:
class Solution {
public:
int jump(vector<int>& nums) {
int cur=0;
int last=0;
int count=0;
for(int i=0;i<nums.size();i++)
{
if(i>last)
{
last=cur;
count++;
}
cur=max(cur,nums[i]+i);
}
return count;
}
};