算法第16周Jump Game II[hard]

来源:互联网 发布:淘宝上为啥不卖电视棒 编辑:程序博客网 时间:2024/06/16 06:21

Description

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

Note:
You can assume that you can always reach the last index.


Solution

这道题目与上一道题目的题意基本相同,只不过这道题目是要计算到达最后位置的最短步数。
我们可以采用BFS的方法,记住每一次的移动都可以到达那些位置。
一开始我想记住每一次可以到达的位置,但最后发现会超时,然后结合本题,我们可以每一次只需记录最远可以到达的位置即可,而不需记录每一个位置。
用curMax记录当前可以到达的最远位置,当前位置为i,i必须小于等于curMax;用nextMax记录移动一步后可以到达的最远位置。要记住,当前位置可以是从i到curMax的任意点。

class Solution {public:    int jump(vector<int>& nums) {        if (nums.size() < 2) return 0;        int result = 0;        int curMax = 0, i = 0, nextMax = 0;        while (i <= curMax) {            result++;            for (;i <= curMax; i++) {                nextMax = max(nextMax, i+nums[i]);                if (nextMax >= nums.size()-1) return result;            }            curMax = nextMax;        }        return 0;    }};
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 狗身上很臭怎么办 被小猫抓伤出血怎么办 被家猫抓伤出血怎么办 家养猫抓伤出血怎么办 狗牙齿划破皮怎么办 被小狗划伤出血怎么办 狗狗一直叫怎么办 出门24小时狗怎么办 卧室空气不流通怎么办 房间不通风潮湿怎么办 屋子空气不流通怎么办 大白天小偷撬门怎么办 家里太热睡不着怎么办 孕妇热的睡不着怎么办 房间里信号不好怎么办 房间里有臭虫怎么办 房间里没有信号怎么办 家里有小虫子怎么办 家里晚上有虫子怎么办 家里厨房有虫子怎么办 屋里好多潮虫子怎么办 发财树长虫子怎么办 大米长虫子了怎么办 家里黑色硬壳虫怎么办 光照色牢度不过怎么办 多肉光照不足怎么办 家里面土鳖虫多怎么办? 蜈蚣爬过皮肤痛怎么办 吃到钢丝球怎么办 吃了钢丝球 怎么办 珍爱网老打电话怎么办 吃了油鱼怎么办 婴儿蜈蚣咬了怎么办 家里有地蜈蚣怎么办 楼房家里有壁虎怎么办 家里老是有壁虎怎么办 家里老断电跳闸怎么办 家里线路跳闸了怎么办 家里连电了怎么办 屋里有臭大姐怎么办 房间里有蜈蚣怎么办