class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
num_5 = 0
num_10 = 0
num_20 = 0
for i in bills:
if i == 5:
num_5 += 1
if i == 10:
num_10 += 1
num_5 -= 1
if i == 20 and num_10 > 0:
num_10 -= 1
num_5 -= 1
elif i == 20 and num_10 == 0:
num_5 -= 3
if num_5 <0 or num_10 <0:
return False
return True
思路就是遍历一次,每次计算剩余的五元和十元的数量,如果数量小于0就return False,遍历完了都没小于0就return True
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x: (-x[0], x[1]))
que = []
for p in people:
que.insert(p[1], p)
return que
思路就是先按身高降序排列,排列完之后,在新的队列按顺序在p[1]的位置插入元素就行
太巧妙了
其中python sort函数的参数:
所以people.sort(key = lambda x: (-x[0], x[1]))就表示对列表每个元素的第一个值进行降序,如果第一个值相同,那么第二个值进行升序
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key = lambda x: x[0])
result = 1
if len(points) == 1:
return result
for i in range(len(points) - 1):
if points[i][1] < points[i + 1][0]:
result += 1
else:
points[i + 1][1] = min(points[i][1], points[i + 1][1])
return result
判断区间是否重叠,就是前一个的右边是否大于等于后一个的左边,如果小于,说明要多一根箭, 如果大于等于,那么就要再判断下一个在不在。
这种情况只要更新一下下一个区间的右边为前两个区间较小的那个,这样到下一次循环的时候就可以自动判断了。