描述
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
思路:
1.记录到现在为止能跳到最远的距离,记为max
2.每一个点能走的步数,记为step,且每往前面走一步,step--
3.判断到这个点后往后跳的步数是不是大于max,如果是就更新max,不是就继续往前走
bool CanJump(int arr[], int size)
{
assert(arr && size>0);
int reach = 1;
for (int i = 0; i < reach && reach < size; i++)
{
reach = (reach>arr[i] ? reach : (arr[i]+i+1));
}
return reach>=size;
}
void test()
{
int arr[5] = { 2, 3, 1, 1, 4 };
cout<<CanJump(arr, 5);
}
int main()
{
test();
return 0;
}