860.柠檬水找零
定义的数组可以直接更改为两个变量,更加清晰直观
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
rest = [0] * 2
for bill in bills:
if bill == 5:
rest[0] += 1
elif bill == 10:
if rest[0] <= 0:
return False
rest[0] -= 1
rest[1] += 1
else:
if rest[0] * 5 + rest[1] * 10 < 15 or rest[0] <= 0:
return False
if rest[1] > 0:
rest[1] -= 1
rest[0] -= 1
else:
rest[0] -= 3
return True
406.根据身高重建队列
完全没想出来,先根据身高进行排序,然后根据人数进行插入
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
# 先按照h维度的身高顺序从高到低排序。确定第一个维度
# lambda返回的是一个元组:当-x[0](维度h)相同时,再根据x[1](维度k)从小到大排序
people.sort(key=lambda x: (-x[0], x[1]))
que = []
for p in people:
que.insert(p[1], p)
return que
452. 用最少数量的箭引爆气球
先按照气球开始坐标排序,然后根据气球的重叠右边界进行判断是否需要增加箭
代码的技巧很强,多学习
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key=lambda x: x[0])
result = 1
for i in range(1, len(points)):
if points[i][0] > points[i-1][1]:
result += 1
else:
points[i][1] = min(points[i][1], points[i-1][1])
return result