소프트웨어에 대한 모든 것

1834. Single-Threaded CPU 본문

알고리즘/LeetCode

1834. Single-Threaded CPU

앤테바 2023. 1. 2. 09:26
반응형

제목

문제)

1834. Single-Threaded CPU

 

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 i​​​​​​th​​​​ 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.

 

Example 1:

Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows: 
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.

Example 2:

Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.

 

Constraints:

  • tasks.length == n
  • 1 <= n <= 105
  • 1 <= enqueueTimei, processingTimei <= 109

 

솔루션1)

- TLE 발생

class Solution:
    def getOrder(self, tasks: List[List[int]]) -> List[int]:
        # tasks with idx
        tasks = [[idx] + task for idx, task in enumerate(tasks)]
        tasks = sorted(tasks, key=lambda x: (x[1], x[2]))        
        
        # initial current time
        cur_time = tasks[0][1]
        
        ret = []
        while len(tasks) > 0:            
            candidates = [[idx] + task for idx, task in enumerate(tasks) if task[1] <= cur_time]
            # print(f'candidates : {candidates}')
            if candidates:
                # by processing time, by index
                candidates = sorted(candidates, key=lambda x: (x[3], x[1]))             
                # print(f'sorted candidates : {candidates}')
                
                cur_time += candidates[0][3]
                ret.append(candidates[0][1])
                # print(f'ret : {ret}')
                del tasks[candidates[0][0]]
                
            else:
                cur_time = tasks[0][0]                
        
        return ret

솔루션2)

- 솔루션1에서 처리해야 할 태스크를 매번 정렬하는 부분이 오버헤드로 판단

- heapq를 사용해서 추가되는 태스크만 정렬하도록 코드 최적화. heapq 정렬시 키는 processingTime, taskIdx를 사용해서 정렬

- TLE는 발생하지 않고 Success는 했지만 여전히 하위 5.72%f로 개선 여지가 많음

class Solution:
    def getOrder(self, tasks: List[List[int]]) -> List[int]:
        EUQUEUE_TIME_IDX = 0
        PROCESSING_TIME_IDX = 1
        TASK_IDX = 2
        
        # tasks with idx
        tasks = [task + [idx] for idx, task in enumerate(tasks)]        
        
        # enqueueTime 오름차순 정렬
        tasks = sorted(tasks, key=lambda x: x[EUQUEUE_TIME_IDX])        
        
        # 초기 시간 설정
        cur_time = tasks[0][EUQUEUE_TIME_IDX]
        
        ret = []
        
        # [key, task]
        candidates = []
        
        while len(tasks):
            # 시간이 지나서 처리해야 할 태스크 후보 등록            
            while tasks and tasks[0][EUQUEUE_TIME_IDX] <= cur_time:
                task = tasks[0]
                key = f'{str(task[PROCESSING_TIME_IDX]).zfill(10)}_{str(task[TASK_IDX]).zfill(6)}'
                heapq.heappush(candidates, [key, task])
                # print(f'heap push - key : {key}, task : {task}')
                del tasks[0]                            
            
            # 태스트 처리
            if candidates and candidates[0][1][EUQUEUE_TIME_IDX] <= cur_time:
                key, task = heapq.heappop(candidates)                
                ret.append(task[TASK_IDX])                
                cur_time += task[PROCESSING_TIME_IDX]
            else:                
                cur_time = tasks[0][EUQUEUE_TIME_IDX]
                
        # 잔여 태스트 모두 처리
        while candidates:
            key, task = heapq.heappop(candidates)            
            ret.append(task[TASK_IDX])            
        
        return ret

솔루션3)

- 솔루션3 리팩토링

class Solution:
    def getOrder(self, tasks: List[List[int]]) -> List[int]:
        EUQUEUE_TIME_IDX = 0
        PROCESSING_TIME_IDX = 1
        TASK_IDX = 2
        
        # tasks with idx
        tasks = [task + [idx] for idx, task in enumerate(tasks)]        
        
        # enqueueTime 오름차순 정렬
        tasks = sorted(tasks, key=lambda x: x[EUQUEUE_TIME_IDX])        
        
        # 초기 시간 설정
        cur_time = tasks[0][EUQUEUE_TIME_IDX]
        
        ret = []                
        candidates = []
        
        while candidates or len(tasks):
            # 시간이 지나서 처리해야 할 태스크 후보 등록            
            while tasks and tasks[0][EUQUEUE_TIME_IDX] <= cur_time:
                task = tasks[0]
                heapq.heappush(candidates, [task[PROCESSING_TIME_IDX], task[TASK_IDX]])
                del tasks[0]                            
            
            # 태스트 처리
            if candidates:
                processing_time, task_idx = heapq.heappop(candidates)                
                ret.append(task_idx)
                cur_time += processing_time
            else:                
                cur_time = tasks[0][EUQUEUE_TIME_IDX]
        return ret

반응형

'알고리즘 > LeetCode' 카테고리의 다른 글

2233. Maximum Product After K Increments  (0) 2023.01.03
520. Detect Capital  (0) 2023.01.02
290. Word Pattern  (0) 2023.01.01
1534. Count Good Triplets  (0) 2022.12.29
1962. Remove Stones to Minimize the Total  (0) 2022.12.29
Comments