Leetcode 45. Jump Game II

题目

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.)
Note:
You can assume that you can always reach the last index.

分析

为了找到跳到最后一步的最小次数,所以可以采用上一题的思想:http://www.jianshu.com/p/eb62990177d9 ,依次保存能够调到最远处的项,按照这个序列跳的时候,次数应该是最小的。

int jump(int* nums, int numsSize) {
    int p=0,ans=0;
    if(numsSize==1)return 0;
    while(p<numsSize)
    {
        if(nums[p]+p>=numsSize-1)
            return ans+1;
        else if(nums[p]==0&&p<numsSize-1)
        {
            return 0;
        }
        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;
            ans++;
        }
        printf("%d\n",p);
    }
    return ans;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容