Leet Code—Jump Game II

本文介绍了一种寻找非负整数数组中从起始位置到达末尾所需的最小跳跃次数的算法。通过维护最大可达距离和当前步骤数,该算法能够在O(n)的时间复杂度内解决问题。文中还提供了两种实现方案的C++代码示例。

摘要生成于 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.)

解题思路:

max_i:表示已经可以到达的最远距离。

min_step:表示当前所走的最少步数。

max_len:表示min_step+1步可以到达的最远距离。

对于每个数组元素,需要考虑如下条件:

1、从当前位置可以到达的最远距离(A[i]+i)小于或等于之前的max_len,并且i没有达到max_i,那么什么也不需要做;

2、如果A[i]+i小于或等于之前的max_len,并且i等于max_i,那么就需要更新max_i的值,并且将min_step加1;

3、如果A[i]+i大于之前的max_len,并且A[i]+i能到达数组尾,那么,如果max_i大于当前的i值,则返回min_step+2。

4、如果A[i]+i大于之前的max_len,并且A[i]+i不能到达数组尾,呢么,如果max_i等于i,则更新max_i的值并将min_step加1,否则什么也不做,继续下一轮循环。

class Solution {
public:
    int jump(int A[], int n) {
        if ((0 == n) || (n == 1)) return 0;
        int max_len = 0;/* 当前能跳的最远距离 */
        int min_step = 0;/* 表示到当前位置最小的跳数 */
        int max_i = A[0];/* 当前一步,达到最大的跨度的下标 */
        for (int i = 0; i < n; i++) {
            if ((A[i]+i <= max_len) && (i != max_i))
                continue;
            else if (A[i]+i <= max_len) {/* reach current scop */
                max_i = max_len;
                min_step++;
            }
            else if (A[i]+i > max_len) {
                max_len = A[i]+i;
                if (i == max_i) {
                    max_i = max_len;
                    min_step++;
                }
                if (max_len >= n-1) {
                    if (n-1 > max_i)
                        min_step++;
                    return (++min_step);
                }
            }
        }
    }
};

如下的解决思路和我的差不多,不过要比我的代码简洁很多:

/*
 * We use "last" to keep track of the maximum distance that has been reached
 * by using the minimum steps "ret", whereas "curr" is the maximum distance
 * that can be reached by using "ret+1" steps. Thus,
 * curr = max(i+A[i]) where 0 <= i <= last.
 */
class Solution {
public:
    int jump(int A[], int n) {
        int ret = 0;
        int last = 0;
        int curr = 0;
        for (int i = 0; i < n; ++i) {
            if (i > last) {
                last = curr;
                ++ret;
            }
            curr = max(curr, i+A[i]);
        }

        return ret;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值