题目链接 | 解题思路
实际上只有三种情况需要讨论:
这道题很符合直觉。
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
records = {5: 0, 10: 0}
for cash in bills:
if cash == 5:
records[5] += 1
if cash == 10:
if records[5] <= 0:
return False
else:
records[5] -= 1
records[10] += 1
if cash == 20:
if records[10] > 0 and records[5] >= 1:
records[10] -= 1
records[5] -= 1
elif records[10] == 0 and records[5] >= 3:
records[5] -= 3
else:
return False
return True
题目链接 | 解题思路
本题明显有两个维度:身高 h 和排序 k。就像发糖果那题一样,都是先处理其中一个维度,然后再处理另一个。由于 k 是依赖于 h 的,优先处理 h 就能更好地利用 k 的信息。
按照身高从大到小排序,如果身高相同则 k 小的优先。排序完成后,依次按照当前的 k 插入队列。因为身高从大到小(相同身高时,k 从小到大),当前插入的 [h, k]
可以确认现在前面有 k 个大于等于 h 的元素,而之后插入的元素必然是小于等于 h的。
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x:(-x[0], x[1]))
result = []
for i in range(len(people)):
result.insert(people[i][1], people[i])
return result
sort(key=lambda x:(-x[0], x[1]))
,优先按照 x[0]
从大到小进行排列,如果 x[0]
相同,则按照 x[1]
从小到大进行排列。
精妙的语法!
按照身高进行从小到大的排序,将元素按照 k 的大小插入当前可以使用的空位。由于保证了之后插入的值都会比现在大,不会出现 k 的冲突。
例如,people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
,过程会是
[[-1, -1],[-1, -1],[-1, -1],[-1, -1],[4, 4],[-1, -1]]
[[5, 0],[-1, -1],[-1, -1],[-1, -1],[4, 4],[-1, -1]]
[[5, 0],[-1, -1],[5, 2],[-1, -1],[4, 4],[-1, -1]]
[[5, 0],[7, 0],[5, 2],[6, 1],[4, 4],[-1, -1]]
[[5, 0],[7, 0],[5, 2],[6, 1],[4, 4],[7, 1]]
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x:x[0])
result = [[-1, -1]] * len(people)
available = [True] * len(people)
temp_saved = []
for i in range(len(people)):
if i == 0 or people[i][0] != people[i-1][0]:
for j in temp_saved:
available[j] = False
temp_saved = []
curr_idx = 0
k = 0
while not available[k]:
k += 1
while curr_idx < people[i][1]:
k += 1
if available[k]:
curr_idx += 1
result[k] = people[i]
temp_saved.append(k)
return result
题目链接 | 解题思路
将气球按照区间的结尾进行排序:如果检查到了区间终点,一个气球还没被射破,那就一定要在这个结尾处射一支箭,否则会无法射破所有气球。而如果这支箭射破了其他的气球,那么就可以直接跳过那些气球。
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key=lambda x:x[1])
count = 0
curr_idx = 0
while curr_idx < len(points):
arrow_x = points[curr_idx][1]
curr_idx += 1
count += 1
while curr_idx < len(points) and points[curr_idx][0] <= arrow_x:
curr_idx += 1
return count