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
相关推荐
Navigator_Z1 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2081 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2082 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2082 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
闲云自留地6 小时前
Kubernetes 安装保姆级:关 swap、装 containerd、init 集群、calico 一篇通
容器·贪心算法·kubernetes
局部有解7 小时前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil2089 小时前
leetcode 75颜色分类
数据结构·算法·leetcode
aqiu11111110 小时前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表
不会就选b10 小时前
算法日常・每日刷题--<动态规划>29
数据结构·算法·leetcode
虚无的纽扣11 小时前
【力扣刷题】第五天:将 x 减到 0 的最小操作数、最大连续1的个数 III
算法·leetcode·职场和发展