算法分析与设计week04--55.Jump Game

本文解析了跳跃游戏问题,采用两种贪心算法实现解决方案。一种是从前往后遍历,记录可达最远距离;另一种是从后往前遍历,寻找最近可达的安全位置。

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

55.Jump Game

Description

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.
Determine if you are able to reach the last index.

Example

A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

Analyse

题意:
给出一个非负数组,初始位置为数组的第一个位置,数组中的元素表示你能跳的最远距离。问是否可以到达最后一个索引位置。

贪心算法:
第一步:从第一个位置开始,计算从该位置出发所能到达的最远距离,然后和sums.length - 1作比较:
“局部最优和全局最优解法”:维护一个到目前为止能跳到的最远距离,以及从当前一步出发能跳到的最远距离。局部最优local = sums[i] + i,而全局最优则是global = max(global, local)。

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int local = 0;
        int global = 0;
        for (int i = 0; i < nums.size(); i++) {

            if (global < i) break;  //  任意 i 位置出现maxstep为0的情况,则说明无法继续向前移动

            local = i + nums[i];
            global = max(global, local);
        }

        return nums.size() - 1 <= global;
    }
};

复杂度分析

时间复杂度:O(n)
空间复杂度:O(1)

另一种贪心解法:逆向考虑

(官网参考答案:https://leetcode.com/problems/jump-game/solution/)
From a given position, when we try to see if we can jump to a GOOD position, we only ever use one - the first one (see the break statement). In other words, the left-most one. If we keep track of this left-most GOOD position as a separate variable, we can avoid searching for it in the array.

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int lastPos = nums.size() - 1;
        for (int i = lastPos; i >= 0; i--) {
            if (i + nums[i] >= lastPos) {
                lastPos = i;
            }
        }
        return lastPos == 0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值