【Leetcode】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.)

题意:给你一个数组,由数组起点0开始,每次可走的长度为0至所在位置的元素大小,问最少需要多少步可以走到终点?

一开始想到了递归的方法,但是很显然,这会超时,下面是超时的方法。

class Solution {
public:
    int jump(int A[], int n) {
        return Jump(A,n,0);
    }
    
    int Jump(int a[],int n,int pos)
    {
        if(pos>=n-1)
            return 0;
        int count=1;
        int m=a[pos];
        if(m==0)
            return n;
        int min=n;
        for(int i=m;i>=1;i--)
        {
            int temp=Jump(a,n,pos+i);
            if(temp<min)
                min=temp;
        }
        count+=min;
        return count;
    }
};

正确的方法是使用贪心算法。

使用两个指针start和end,维护一个最大覆盖区间,每次扫描时,都动态改变区间的边界。例如,在扫描A[start]至A[end]时,每次都计算A[i]+i的值,取得其最大值作为下次扫描的end边界,下次的start边界即为上次end+1,直到end>n。

class Solution {
public:
    int jump(int A[], int n) {
        int start=0;
        int end=0;
        int count=0;
        if(n==1)
            return 0;
        while(end<n)
        {
            count++;
            int max=0;
            for(int i=start;i<=end;i++)
            {
                if(A[i]+i>=n-1)
                    return count;
                if(A[i]+i>max)
                    max=A[i]+i;
            }
            start=end+1;
            end=max;
        }
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值