首页 > 其他 > 详细

leetcode 45. Jump Game II

时间:2019-06-17 17:53:22      阅读:126      评论:0      收藏:0      [点我收藏+]

题目

Jump Game II

题目就是从位置0开始 跳到位置n-1, 每次在位置i 可以跳的最远位置为 i+nums[i]

思路和代码

参考自 leetcode most vote

The main idea is based on greedy. Let‘s say the range of the current jump is [curBegin, curEnd], curFarthest is the farthest point that all points in [curBegin, curEnd] can reach. Once the current point reaches curEnd, then trigger another jump, and set the new curEnd with curFarthest, then keep the above steps, as the following:

class Solution {
public:
    int jump(vector<int>& nums) {
        int n = nums.size();
        if (n == 0) return 0;
        int res = 0,end = 0, mx = 0;
        for(int i=0; i<n-1; i++) {
            mx = max(i+nums[i], mx);
            if(i == end) {
                res++;
                end = mx;
            }
        }
        return res;
    }
};

leetcode 45. Jump Game II

原文:https://www.cnblogs.com/Draymonder/p/11040491.html

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