LeetCode刷题笔录 Jump Game II

26 篇文章 0 订阅
14 篇文章 0 订阅

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.)

拿到这题,第一反应就是dynamic programming了。以x[i]表示第i个element需要的最少步数,有这样的递归方程:

x[i] = min(x[k]) + 1 where 0<=k<i and A[k] >= i-k.

迅速写出代码:

public class Solution {
    public int jump(int[] A) {
        int x[] = new int[A.length];
        x[0] = 0;
        for(int i = 1; i < x.length; i++){
            //find the min x[k]
            int min = Integer.MAX_VALUE;
            for(int k = 0; k < i; k++){
                if(A[k] < i - k)
                    continue;
                else{
                    if(x[k] < min)
                        min = x[k];
                }
            }
            x[i] = min + 1;
        }
        return x[x.length - 1];
    }
}
问题是,在一个有25000个元素的test case里因为超时挂掉了。。。这个算法用O(n^2)时间,想了半天也不知道如果用dp的话还能怎么改进了。

其实这题里面每个数字表示的是能跳得最大距离,而不是只能跳这么远。而且最后也没有要求怎么跳,用dp有点大材小用了。看到大神的解法,用贪心就行其实。

public class Solution {
    public int jump(int[] A) {
        int ret = 0;
        int last = 0;
        int curr = 0;
        for (int i = 0; i < A.length; ++i) {
            if (i > last) {
                last = curr;
                ++ret;
            }
            curr = Math.max(curr, i+A[i]);
        }

        return ret;
    }
}

觉得自己真是弱爆了...

另外找到这篇blog用中文解释了一下这个解法。

果然自己好弱。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值