【leetcode】45. Jump Game II 非负数组的最少跳跃步数

1. 题目

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.

2. 思路

第一个节点必须要进入,每次进入一个起点i之后,下一步的落点可以是[i+1, i+nums[i]],找到这个范围内的可以跳跃最远的点作为下一步。循环直到跳跃到最后。

3. 代码

耗时:13ms

class Solution {
public:
    // 当做到第i步时,此时最大可以跳跃到的点时i+a[i]; 
    // 下一步找到[i, i+a[i]]之间的最大可跳跃点, 下一步选择这个最大点
    // 循环往复直到到最后一个点
    int jump(vector<int>& nums) {
        int sz = nums.size();
        if (sz <= 1) { return 0; }
        int k = 0;
        int i = 0;
        int i_max = 0;
        while (i < sz - 1) {
            k++;
            int i_max = i + nums[i]; // 当前跳跃段的起点
            if (i_max >= sz - 1) { break; }
            int j_max = -1;
            int j_max_idx = -1;
            for (int j = i + 1; j <= i_max && j < sz; j++) { // 选择[i, i+nums[i]]段内的最大跳跃点作为下一点
                int tmp_max = j + nums[j];
                if (tmp_max > j_max) {
                    j_max = tmp_max;
                    j_max_idx = j;
                }
            }
            i = j_max_idx;
        }
        
        return k;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值