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

Jump Game II

时间:2015-09-15 16:39:17      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:represents   example   element   number   minimum   

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

标签:represents   example   element   number   minimum   

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

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