首页 > 其他 > 详细

Jump Game II

时间:2015-09-15 16:37:45      阅读:181      评论:0      收藏:0      [点我收藏+]

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

解法:

利用层次遍历,bfs算法,把第i+1层定义为第i层可以达到的最远位置内的点,2|3,1|1,4  则需要两次

2 第一层,

3,1 第二层

1,4 第3层  从第一层跳到第3层,需要2步


代码

int jump(vector<int>& nums) {

        int size=nums.size();

        if(size<2)

            return 0;

        

        int level=0,curmaxreach=0,nextmaxreach=0;

        int pos=0;

        while(curmaxreach-pos+1>0){//每层节点数,如果该层节点数为0,说明由上一层以及无法进入下一层,结束,可以返回MAX_INT

            level++;

            for(;pos<=curmaxreach;++pos){//必须含有=

                nextmaxreach=max(nextmaxreach,nums[pos]+pos);

                if(nextmaxreach>=size-1)

                    return level;

            }

            curmaxreach=nextmaxreach;

        }

        

        return numeric_limits<int>::max();

    }


Jump Game II

原文:http://searchcoding.blog.51cto.com/1335412/1694962

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!