leetcode : Jump Game I&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.

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.

I是判断能否到达最后一个位置,II是保证能到最后一个位置,求最小步数

Jump Game I 很简单,每次保存能达到的最右边的位置,遍历完一遍数组看这个位置是否超过了最后一个位置即可,

AC代码:

class Solution {
public:
    bool canJump(int A[], int n) {
        int end = 0;
        for(int i = 0; i < n; ++i){
            if(i <= end)
                end = max(end, A[i] + i);
            else
                return false;
        }
        return true;
    }
};

Jump Game II是要求最小步数,用动态规划,dp[i]表示从0到i的最小步数,用right保存从当前已经走过的节点能到达的最远位置,这样只有在最远位置更新的时候,才需要更新dp数组。

由于整个dp数组都只被写了一次,所以复杂度为O(n)

这个题写的时候忘记更新right,导致一直超时,以为自己算法错了,然后看了别人的AC代码,尼玛复杂度为N^2的都过了。。。

A题之前还是得把思路都想清楚,证明方法可行之后再写代码-。-磨刀不误砍柴工~~~

AC代码:

class Solution {
public:
    int jump(int A[], int n) {
        vector<int> steps(n, 0);
        int right = 0;
        steps[0] = 0;
        for(int i = 0; i < n; ++i){if(A[i] + i > right){
                for(int j = right + 1; j < n && j <= A[i] + i; ++j){
                    steps[j] = steps[i] + 1;
                }
                right = A[i] + i;
            }
        }
        return steps[n - 1];
    }
};

 

posted on 2014-12-09 23:06  远近闻名的学渣  阅读(147)  评论(0)    收藏  举报

导航