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.)
题目解析:
jump函数出现了超时的错误,因为时间复杂度不是O(n)的。
第二种方法
jump2
通过计算1步,2步,...,n步所得到达的最大距离,时间复杂度为O(n)
#include <iostream>
using namespace std;
int jump(int A[], int n) {
int *memory = (int *)malloc(sizeof(int)*(n));
memory[n-1] = 0;
for(int i=n-2;i>=0;i--)
{
if(A[i] == 0)
{
memory[i] = INT_MAX;
}else{
int steps = A[i];
int minStep = INT_MAX;
int currIndex = i;
while(steps > 0 && currIndex <=(n-1))
{
steps--;
currIndex++;
if(A[currIndex]!=0 && memory[currIndex]+1 < minStep)
minStep = memory[currIndex]+1;
}
while(steps > 0)
{
}
memory[i] = minStep;
}
}
return memory[0];
}
int jump2(int A[], int n) {
if (A == NULL || n <= 1) {
return 0;
}
int tail = A[0];
int begin = 1;
int minStep = 1;
while(tail < n-1)
{
int maxDest = 0;
for(int i=begin ;i<=tail;i++)
{
maxDest = max(maxDest,i+A[i]);
}
begin = tail + 1;
tail = maxDest;
minStep++;
}
return minStep;
}
int main(void)
{
int A[] = {1,1,1,1,1};
int n = sizeof(A)/sizeof(int);
cout <<jump2(A, n) << endl;
system("pause");
return 0;
}