LeetCode 860. 柠檬水找零
有如下三种情况:
- 情况一:账单是5,直接收下。
- 情况二:账单是10,消耗一个5,增加一个10
- 情况三:账单是20,优先消耗一个10和一个5,如果不够,再消耗三个5
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
count = {5:0, 10:0, 20:0}
for i in range(len(bills)):
# 1. 收到5元
if bills[i] == 5:
count[5] += 1
# 2. 收到10元
elif bills[i] == 10:
if count[5] == 0:
return False
else:
count[5] -= 1
count[10] += 1
# 3. 收到20元
elif bills[i] == 20:
# 优先找10元的
if count[10] > 0 and count[5] > 0:
count[10] -= 1
count[5] -= 1
count[20] += 1
# 再尝试找3个5元的
elif count[10] == 0 and count[5] >= 3:
count[5] -= 3
count[20] += 1
else:
return False
return True
LeetCode 406.根据身高重建队列
- 本题首先对身高从高到低排序,同时前面的人数按从低到高排。此时身高相同的人的相对位置就是正确的,并且每个人前面身高大于自己的人数是最多的情况
- 此时只需要从前向后遍历判断每个人前面的人数是否是正确的,如果不正确则向前移动即可。向前移动是不会影响前面每个人的身高大于自己的数目的,因为当前移动人的身高比前面所有人都矮
# 原地修改people
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x: (-x[0], x[1]))
for i in range(len(people)):
if people[i][1] != i:
idx = people[i][1]
people = people[0:idx] + [people[i]] + people[idx:i] + people[i+1:]
return people
# 创建新的列表插入
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 = []
# 根据每个元素的第二个维度k,贪心算法,进行插入
# people已经排序过了:同一高度时k值小的排前面。
for p in people:
que.insert(p[1], p)
return que
LeetCode 452. 用最少数量的箭引爆气球
力扣题目链接
本题还是区间调度问题,求最多互不相交的区间,唯一的区别是区间的边界,如果箭头触碰到气球的边界也会爆炸,所以边界触碰也算重叠。
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
if not points: return 0
points.sort(key=lambda x: x[1])
count = 1
x_end = points[0][1]
for i in range(1, len(points)):
if points[i][0] > x_end: # 只需把 >= 改成 >
count += 1
x_end = points[i][1]
return count
今日毕!