Leetcode_jump-game-ii(c++ and python version)

来源:互联网 发布:淘宝怎么买电鸡 编辑:程序博客网 时间:2024/04/29 20:39

地址:http://oj.leetcode.com/problems/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.)

思路:记录当前的位置cur,和当前通过走一步能走到的最远位置farthest,下一次cur的起点是nxt
            farthest赋值给nxt后,farthest更新
c++参考代码:
class Solution {public:    int jump(int A[], int n) {        if(n==1)            return 0;        int cur = 0, nxt = 0, farthest = 0, ans = 0;        while(cur <= farthest)        {            ++ans;            nxt = farthest+1;            for(int i = cur; i<nxt; ++i)            {                if(i+A[i]>farthest)                {                    farthest = i+A[i];                    if(farthest>=n-1)                        return ans;                }            }            cur = nxt;        }    }};

python参考代码:
class Solution:    # @param A, a list of integers    # @return an integer    def jump(self, A):        if not A or len(A)==1 : return 0        ans = cur = farthest = 0        while cur <= farthest:            ans += 1            nxt = farthest + 1            for i in range(cur, nxt):                if i+A[i]>farthest:                    farthest = i + A[i]                    if farthest >= len(A)-1:                        return ans            cur = nxt


//SECOND TRIAL
class Solution {
public:
    int jump(int A[], int n) {
        if(n==1)
            return 0;
        if(A[0]>=n-1)
            return 1;
        int ans = 1, begin = 0, end = A[0], step = 0;
        while(1)
        {
            while(begin<=end)
            {
                step = max(step, begin+A[begin]);
                ++begin;
            }
            if(step>=n-1)
                return 1+ans;
            begin = end;
            end = step;
            ++ans;
        }
    }
};


0 0
原创粉丝点击