[leetcode]Jump Game II

题目

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.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

思路

注意到,题目有这样一个性质:若我们走的步数记作step,可以到达某个位置,那么走到这个位置之前的位置最多不超过step步。
这启发我们采用下面的算法,从数组头开始往后扫描,记录在当前所走的步数下(记作step),所能走到的最远位置(记作end)。同时我们维护一个farthest变量,表示再走一步,点最远可以到达地方的下界。当扫描到end的时候,farthest变成下一步最远可到达的地方,此时更新step加一,end=farthest。当end已经达到或超过数组最后一个元素时,返回的step,即是到达数组最后位置需要跳动的最小步数。

代码

class Solution {
public:
    int jump(vector<int>& nums) {
        int step = 0;
        int end = 0;
        int farthest = 0;
        for (int i = 0; i != nums.size(); ++i) {
            if (end >= nums.size() - 1) {
                break;
            }
            if (i + nums[i] > farthest) {
                farthest = i + nums[i];
            }
            if (i == end) {
                ++step;
                end = farthest;
            }
        }
        return step;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值