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.)
题意:给你一个数组,由数组起点0开始,每次可走的长度为0至所在位置的元素大小,问最少需要多少步可以走到终点?
一开始想到了递归的方法,但是很显然,这会超时,下面是超时的方法。
class Solution {
public:
int jump(int A[], int n) {
return Jump(A,n,0);
}
int Jump(int a[],int n,int pos)
{
if(pos>=n-1)
return 0;
int count=1;
int m=a[pos];
if(m==0)
return n;
int min=n;
for(int i=m;i>=1;i--)
{
int temp=Jump(a,n,pos+i);
if(temp<min)
min=temp;
}
count+=min;
return count;
}
};
正确的方法是使用贪心算法。
使用两个指针start和end,维护一个最大覆盖区间,每次扫描时,都动态改变区间的边界。例如,在扫描A[start]至A[end]时,每次都计算A[i]+i的值,取得其最大值作为下次扫描的end边界,下次的start边界即为上次end+1,直到end>n。
class Solution {
public:
int jump(int A[], int n) {
int start=0;
int end=0;
int count=0;
if(n==1)
return 0;
while(end<n)
{
count++;
int max=0;
for(int i=start;i<=end;i++)
{
if(A[i]+i>=n-1)
return count;
if(A[i]+i>max)
max=A[i]+i;
}
start=end+1;
end=max;
}
}
};