您的位置:首页 > 编程语言 > C语言/C++

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

2014-05-05 13:51 417 查看
地址: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 TRIALclass 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;        }    }};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: