一、貪心算法問題
1. 跳躍游戲系列
- 能否到達終點:
def canJump(nums):max_reach = 0for i in range(len(nums)):if i > max_reach:return Falsemax_reach = max(max_reach, i + nums[i])return True
- 最少步數:
def jump(nums):jumps = end = max_pos = 0for i in range(len(nums)-1):max_pos = max(max_pos, i + nums[i])if i == end:jumps += 1end = max_posreturn jumps
2. 分發餅干
- 解法:排序+雙指針
def findContentChildren(g, s):g.sort()s.sort()i = j =