題目
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.
分析
給定一個(gè)數(shù)組,每個(gè)數(shù)值代表最大的移動(dòng)長(zhǎng)度,確定能不能走到最后一個(gè)元素。
采用貪心思想富稻,依次尋找能夠走到當(dāng)前最遠(yuǎn)處的那個(gè)元素,直到該元素為最后一個(gè)或者為0坷备。
還有其他方式祖今,比如依次遍歷暴区,并更新當(dāng)前能走的最遠(yuǎn)距離懦趋,直到無法走下去為止晾虑。
bool canJump(int* nums, int numsSize) {
int p=0;
while(p<numsSize)
{
if(nums[p]+p>=numsSize-1)
return true;
else if(nums[p]==0&&p<numsSize-1)
{
return false;
}
else
{
int temp=nums[p],max=0,p1=0;
for(int i=0;i<temp;i++)
{
p++;
if(nums[p]+1+i-temp>=max)
{
max=nums[p]+1+i-temp;
p1=p;
}
}
p=p1;
}
printf("%d\n",p);
}
return false;
}