classGetOrder:"""
1834. 单线程 CPU
https://leetcode.cn/problems/single-threaded-cpu/description/
"""defsolution(self, tasks):
n =len(tasks)# 把原始索引也添加上,方便后面排序用
triples =[(tasks[i][0], tasks[i][1], i)for i inrange(n)]# 数组先按照任务的开始时间排序
triples.sort(key=lambda x: x[0])# 使用 heapq 来实现 PriorityQueueimport heapq
pq =[]# 初始化结果列表和完成时间线
res =[]
now =0
i =0whilelen(res)< n:if pq:# 完成队列中的一个任务
item = heapq.heappop(pq)
res.append(item[1])# 每完成一个任务,就要推进时间线
now += item[0]elif i < n and triples[i][0]> now:# 队列为空可能因为还没到开始时间,# 直接把时间线推进到最近任务的开始时间
now = triples[i][0]# 由于时间线的推进,会产生可以开始执行的任务while i < n and triples[i][0]<= now:
heapq.heappush(pq,(triples[i][1], triples[i][2], triples[i][0]))
i +=1return res