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.
For example:
Given array A =[2,3,1,1,4]
The minimum number of jumps to reach the last index is2. (Jump1step from index 0 to 1, then3steps to the last index.)

给定一个非负整数数组,最初定位在数组的第一个索引处。 数组中的每个元素表示您在该位置的最大跳跃长度。 你的目标是达到最小跳跃次数的最后一个索引。 例如:给定数组A = [2,3,1,1,4]到达最后一个索引的最小跳转次数是2。 (从索引0跳到1,然后3步到最后一个索引。)

解题思路

只要能够到达的最远距离还没有到n,就必须再走下一步。所以只需要在上一道题程序的基础上,加入计数,并且更新最后一个跳点即可。

C++版代码实现

class Solution {
public:
    int jump(int A[], int n) {
        if(A == NULL || n == 0)
            return false;
        //maxReach标记能跳到的最远处。
        int maxReach = 0, curReach = 0, steps = 0;
        //maxReach >= i表示此时能跳到i处,0 <= i < n表示扫描所有能到达的点,并计算能达到的最远距离。
        for(int i = 0; i < n && i <= maxReach; ++i) {
            if(i > curReach){
                ++steps;
                curReach = maxReach;
            }
            maxReach = max(maxReach, A[i] + i);
        }
        //如果最后跳的最远的结果大于等于n-1,那就能跳到最后。
        return maxReach < n - 1 ? false : steps;
    }
};

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值