题目:
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.)
用贪心策略,选择跳到下一步能跳到最远的距离。复杂度是最小步数乘以n,最坏是O(n²)。
代码:
class Solution {
public:
int jump(vector<int>& nums) {
int i=0,step=0;
while(i<nums.size()-1)
{
int max_index=i+1;
for(int j=i+1;j<=i+nums[i];j++)
{
if(j>=(nums.size()-1)||((nums[max_index]+max_index)<(j+nums[j]))) max_index=j;
}
i=max_index;step++;
}
return step;
}
};
还有O(n)的解法:记录目前的步数、上一个步数能到的最远距离、这个步数能到的最远距离。从左到右扫描数组,如果上一步不能到达某个点,步数加1。具体看代码。交了发现比解法一还慢。
代码:
class Solution {
public:
int jump(vector<int>& nums) {
int step=0;
int preReach=-1;//上一步(step-1)能走到的最远距离
int curReach=0;//这一步(step)能走到的最远距离
for(int i=0;i<nums.size()-1;i++)
{
if(curReach>=nums.size()-1) return step;
if(i>preReach)//只用step-1步不能走到这里
{
step++;
preReach=curReach;
}
curReach=max(curReach,i+nums[i]);//只用step步可能还可以多走一点
}
return step;
}
};