Leetcode 55. Jump Game

题目

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.

分析

给定一个数组,每个数值代表最大的移动长度,确定能不能走到最后一个元素。
采用贪心思想,依次寻找能够走到当前最远处的那个元素,直到该元素为最后一个或者为0。
还有其他方式,比如依次遍历,并更新当前能走的最远距离,直到无法走下去为止。

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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容