【LeetCode】45. Jump Game II (Hard)

本文介绍了一个算法问题,即如何在给定的非负整数数组中找到从起始位置到达最后一个元素所需的最少跳跃次数。通过贪心策略逆向计算,确保路径选择的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】

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.

【解】

从最后的位置往前推,贪心记录能到达这个位置的最靠前的一个的下标。

A = [2, 3, 1, 1, 4],对应的 V = [-1, 0, 0, 1, 1]

然后从后往前推,数几步能到第一个位置(-1)

求V:从第一个数开始,A[0] = 2,能到达的位置有0, 1和2,然后下一个数A[0] = 3,0, 1, 2这3个位置已经可以从位置0达到,所以从位置3开始看能否达到,然后给V赋值......

给V赋值的时候只顺序做了一次,所以时间复杂度应该是O(n)?  ,空间复杂度O(n)

class Solution {
public:
    int jump(vector<int>& nums) {
        int n = nums.size();
        vector<int> v(n);
        v[0] = -1;
        int t = 0;
        for (int i = 0; i < n; i++) {
            int a = nums[i];
            if (a + i > t) {
                int j;
                for (j = t + 1; j <= a + i && j < n; j++) {
                    v[j] = i;
                }
                t = j - 1;
            }
        }
        int i = v[n - 1];
        int cnt = 0;
        while (i != -1) {
            i = v[i];
            cnt++;
        }
        return cnt;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值