860. Lemonade Change
局部最优:遇到账单20,优先消耗美元10,完成本次找零。
全局最优:完成全部账单的找零。
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
five, ten, twenty = 0, 0, 0
for bill in bills:
if bill == 5:
five += 1
if bill == 10:
if five < 1: return False
five -= 1
ten += 1
if bill == 20:
if ten >= 1: # 先看是否有10元可以消耗
ten -= 1
if five >= 1:
five -= 1
else:
return False
else:
if five < 3:
return False
else:
five -= 3
twenty += 1
return True
406. Queue Reconstruction by Height
局部最优:优先按身高高的people的k来插入。插入操作过后的people满足队列属性
全局最优:最后都做完插入操作,整个队列满足题目队列属性
Python中sort() 中key的用法
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
def rule(p):
'''
定义规则,优先身高从大到小,其次k小的站前面
'''
return -p[0], p[1]
people.sort(key = rule)
# people.sort(key=lambda x: (-x[0], x[1]))
res = []
for p in people:
res.insert(p[1], p)
return res
452. Minimum Number of Arrows to Burst Balloons
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
# 按气球Xstart排序
points.sort(key = lambda x:x[0])
res = 1 # points 不为空至少需要一支箭
for i in range(1, len(points)):
# 和前一个没有重叠,需要一只箭
if points[i][0] > points[i - 1][1]:
res += 1
else:
points[i][1] = min(points[i][1], points[i - 1][1]) # 更新重叠气球最小右边界
return res