LeetCode刷题笔录 Jump Game II

来源:互联网 发布:淘宝crm软件排名 编辑:程序博客网 时间:2024/06/05 07:13

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用中文解释了一下这个解法。

果然自己好弱。

0 0
原创粉丝点击