45. Jump Game II

来源:互联网 发布:淘宝3天不发货怎么投诉 编辑:程序博客网 时间:2024/05/16 15:55

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

题目大意:题目有解释,不解释了。
思路:先算出当前位置与lastIdx之间的距离,如果小于等于0,只要jump1次就是可以,否则找出接下来可以走的几步,哪一步离lastIdx的更近。比如例子,从起始开始lastIdx=4,最初的min = 4 - (pos + nums[pos]) = 2, 然后可以走两步或者1步,1步的话离dis = 4 - (1 + 3)比min小,两步的话,dis = 4 - (2 +1) = 1。那么就走1步。接下来一直这样走直到结束

class Solution {public:    int jump(vector<int>& nums) {        int nowIdx = 0, lastIdx = nums.size() - 1, cnt = 0, min = 0x7fffffff, idx;        while(nowIdx < lastIdx){            min = lastIdx - (nowIdx + nums[nowIdx]);            idx += nums[nowIdx];            if(min <= 0)                return ++cnt;            for(int i = nowIdx + 1; i <= nowIdx + nums[nowIdx] && i < lastIdx; ++i){                if(lastIdx - (i + nums[i]) < min){                    min = lastIdx - (i + nums[i]);                    idx = i;                }            }            ++cnt;            nowIdx = idx;        }        return cnt;    }};
0 0
原创粉丝点击