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
相关推荐
蛋蛋的就会顺顺的14 小时前
hot100——矩阵
java·数据结构·算法·leetcode·力扣
想吃火锅100519 小时前
【leetcode】238.除了自身以外数组的乘积js
javascript·算法·leetcode
Tisfy20 小时前
LeetCode 0020.有效的括号:栈匹配
算法·leetcode·字符串·题解·括号匹配
Navigator_Z20 小时前
LeetCode //C - 1276. Number of Burgers with No Waste of Ingredients
c语言·算法·leetcode
想吃火锅100521 小时前
【leetcode】189.轮转数组js
开发语言·javascript·leetcode
All for pursuit.1 天前
【贪心-2】253.会议室 II
数据结构·c++·算法·leetcode
Zhu7581 天前
离线二进制部署-Kubernetes-v1.36.4
容器·贪心算法·kubernetes
All for pursuit.2 天前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
Elastic 中国社区官方博客2 天前
Kubernetes attributes processor v1:它对 EDOT Collector 意味着什么
java·大数据·elasticsearch·搜索引擎·贪心算法·kubernetes·全文检索
All for pursuit.2 天前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode