频道栏目
首页 > 资讯 > 其他 > 正文

leetcode No45. Jump Game II

16-11-03        来源:[db:作者]  
收藏   我要投稿

Question:

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 is2. (Jump1step from index 0 to 1, then3steps to the last index.)

Algorithm:

1、记录当前可到达的最大距离,和上一次可到达的最大距离
2、如果上一跳已经到不了当前的位置,则需要进行一次跳跃

Accepted Code:

class Solution {  
public:  
    int jump(vector<int>& nums) {  
        int step = 0;        //当前跳数  
        int curMax = 0;      //当前可达到的最远距离  
        int preMax = 0;      //上一跳可达到的最远距离  
        for(int i=0;i<nums.size();i++){  
            if(curMax<i)     //当前可达到的最大距离到不了i,所以返回-1   
                return -1;  
            if(preMax<i){    //上一跳可达到的最大距离到不了i,所以要跳一步,更新step和preMax  
                step++;  
                preMax=curMax;  
            }  
            curMax=max(curMax,i+nums[i]);   //记录可到达的最大距离  
        }  
          
        return step;  
    }  
};
相关TAG标签
上一篇:SSM框架项目搭建系列(二)—Spring第一个HelloWorld
下一篇:Client-ServerRSA加解密通信方案-Server端(C++)(一)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站