LeetCode 55. Jump Game(跳跃游戏Ⅰ)

本文解析了跳跃游戏的问题,采用贪心算法解决能否从数组起点到达终点的挑战。通过维护可达最远距离来判断是否存在可行路径。

摘要生成于 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.
    Determine if you are able to reach the last index.
    For example:
        A = [2,3,1,1,4], return true.
        A = [3,2,1,0,4], return false.

分析:
    题意:给定一个非负整型数组A,大小为n。A[i]表示从i位置出发的最大跳跃步数。判断是否能从0点出发,到达n - 1点。
    思路:这道题时LeetCode 45的进化版本。思路都是贪心算法,具体细节这里不再详细复述,主要讲跟LeetCode 45的区别:对于每一个位置i,我们用pre表示i之前能够达到的最远位置,cur表示包含从i出发的情况,此时能够到达的最远位置。① 如果i > pre,则说明当前i位置已经超出了前一步的最远跳跃点,无法完成衔接,因此无法到达n - 1点;② i的取值范围考虑为0→n - 1而不是0n - 2,因为最后一步也要判断,之前的最大跳跃点能否到达。
    时间复杂度为O(n)。

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int n = nums.size();
		// Exceptional Case: 
		if(n <= 1){
			return true;
		}
		int preMaxEnd = 0, curMaxEnd = 0;
		// for(int i = 0; i <= n - 2; i++){ will cause an error!
		for(int i = 0; i <= n - 1; i++){
			if(i > preMaxEnd){
				return false;
			}
			curMaxEnd = max(curMaxEnd, i + nums[i]);
			if(i == preMaxEnd){
				preMaxEnd = curMaxEnd;
			}
		}
		return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值