码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Jump Game II

时间:2014-05-31 03:14:14      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

 

原本使用一种动态规划做法。开辟jump数组,将数组A从后往前遍历,jump[i]存储第[i]个元素到A[n-1]的最小jump数。

因此jump[i-1]就是A[i-1]jump范围内最小jump值+1.可惜TLE了。

 

最优美的解法与Jump Game类似,从前往后遍历一次,记录几个关键点就够了:

jump:目前为止的jump数

lastMax:从A[0]进行jump次jump之后达到的最大范围

curMax:从0~i这i+1个A元素中能达到的最大范围

当lastMax<i,说明jump次已经不足以覆盖当前第i个元素,因此需要增加一次jump,使之达到

记录的curMax。

bubuko.com,布布扣
class Solution {
public:
    int jump(int A[], int n) {
       int jump = 0;
       int lastMax = 0;    //trace the max with jump times jump
       int curMax = 0;    //trace the max from 0~i

       for(int i = 0; i < n; i ++)
       {
           if(lastMax < i)
           {
                jump ++;            // need a jump!
                lastMax = curMax;    // jump to new max(curMax)
           }
           curMax = max(curMax, A[i]+i);
       }
       return jump;
    }
};
bubuko.com,布布扣

bubuko.com,布布扣

【LeetCode】Jump Game II,布布扣,bubuko.com

【LeetCode】Jump Game II

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/ganganloveu/p/3761715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!