https://leetcode.com/problems/single-threaded-cpu/description/
You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
- If the CPU is idle and there are no available tasks to process, the CPU remains idle.
- If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
- Once a task is started, the CPU will process the entire task without stopping.
- The CPU can finish a task then start a new one instantly.
Return the order in which the CPU will process the tasks.
class Solution:
def getOrder(self, tasks: List[List[int]]) -> List[int]:
tasks = sorted([(task[0], task[1], i) for i, task in enumerate(tasks)]) # et, pt, index
res = []
h = []
T = tasks[0][0]
for et, pt, index in tasks:
while h and T < et:
p, i = heapq.heappop(h)
T += p
res.append(i)
T = max(T, et)
heapq.heappush(h, (pt, index))
while h:
res.append(heapq.heappop(h)[1])
return res
When time is N, there are two situations.
- There are tasks that came in before N,
- CPU just picks up task in queue oredered by (process time, index)
- There aren't tasks that came in before N
- CPU picks up the first task that came in after N.
'algo > leetcode' 카테고리의 다른 글
49. Group Anagrams (1) | 2024.10.13 |
---|---|
2007. Find Original Array From Doubled Array (0) | 2024.08.21 |
837. New 21 Game (0) | 2024.08.18 |
2101. Detonate the Maximum Bombs (0) | 2024.08.15 |
885. Spiral Matrix III (0) | 2024.08.15 |