860. 柠檬水找零
题目链接: 860. 柠檬水找零
这题需要模拟钱币的数量,应该可以想出来,但是还是差了一点。
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 > 2:
five -= 3
else:
return False
return True
406. 根据身高重建队列
题目链接:406. 根据身高重建队列
这题最重要的就是身高由高到低排序,但是前面的人数的由小到大排序,这就是难点,使用sort中key函数来解决。
sort中key函数
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(reverse=True)
people.sort(key=lambda x: (-x[0], x[1]))
res=[]
for i in range(len(people)):
res.insert(people[i][1],people[i])
return res
452. 用最少数量的箭引爆气球
题目链接:452. 用最少数量的箭引爆气球
先排序,排序后的两根箭是否重叠,即i-1的右端点是否小于i的左端点(注意相等的时候也算重叠),重叠则更新i的右端点为min(i-1的右,i的右)。 另外,需要注意起始箭从1开始。
class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: 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