Leecode热题100---55:跳跃游戏(贪心算法)

题目

给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false 。


贪心算法
思路

尽可能到达最远位置(贪心)。

如果能到达某个位置,那一定能到达它前面的所有位置。

C++

cpp 复制代码
class Solution
{
public:
	bool canJump(vector<int>& nums)
	{
		int n = nums.size();
		int r = 0;		// 当前能跳到的最远位置
		for (int l = 0;l < n;l++)
		{
			if(l > r)	// 若跳不到l,则一定跳不到 n-1,即:若中间有任一点跳不到,则一定跳不到最后
			{
				return false;
			}
			r = max(r, l+nums[l]);	// 更新当前最远位置
		}
		return true;
	}
};

python

思路同上

python 复制代码
    # enumerate(iteration, start)
    # 函数默认包含两个参数,其中iteration参数为需要遍历的参数,比如字典、列表、元组等,start参数为开始的参数,默认为0(不写start那就是从0开始)。
    # enumerate函数有两个返回值,第一个返回值为从start参数开始的数,第二个参数为iteration参数中的值。

class Solution:
	def canJump(self,nums):
		max_i = 0		# 初始化当前能到达最远的位置
		# i为当前位置,jump是当前位置的跳数
		for i, jump in enumerate(nums):
			# 如果当前位置能到达,并且当前位置+跳数>最远位置
			if max_i >= i and i+jump > max_i:
				# 更新最远能到达位置
				max_i = i+jump
		 # 比较最远位置和数组长度
		return max_i >= i
相关推荐
leoufung9 小时前
逆波兰表达式 LeetCode 题解及相关思路笔记
linux·笔记·leetcode
Aspect of twilight11 小时前
LeetCode华为大模型岗刷题
python·leetcode·华为·力扣·算法题
2301_8079973811 小时前
代码随想录-day47
数据结构·c++·算法·leetcode
Elias不吃糖11 小时前
LeetCode每日一练(3)
c++·算法·leetcode
小年糕是糕手15 小时前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode
sheeta199821 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!1 天前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi1 天前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
-森屿安年-1 天前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode