目录
860.柠檬水找零
只有5元,10元,20元三种情况。
针对5元,直接增加当前5元的数量;针对10元,减少当前5元的数量,增加当前10元的数量;针对20元,优先消耗10元和5元找零,没有10元则消耗3个5元找零(因为5元用途更广所以要尽量先消耗10元)。代码如下:
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
five, ten = 0, 0
for bill in bills:
if bill == 5:
five += 1
elif bill == 10:
if five < 1:
return False
five -= 1
ten += 1
else:
if ten > 0 and five > 0:
ten -= 1
five -= 1
elif five >= 3:
five -= 3
else:
return False
return True
406.根据身高重建队列
对身高和索引分开处理:先按身高从高到低排列,然后再根据people中每个数据索引值逐个插入。
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x:(-x[0],x[1]))
res = []
for i in people:
res.insert(i[1],i)
return res
452.用最少数量的箭引爆气球
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
if len(points) == 0:
return 0
points.sort(key = lambda x: x[0])
res = 1
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][1], points[i][1])
return res