Skip to content

Latest commit

 

History

History
11 lines (6 loc) · 1.66 KB

File metadata and controls

11 lines (6 loc) · 1.66 KB

621. Task Scheduler

Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.

However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.

Return the least number of units of times that the CPU will take to finish all the given tasks.

My straightforward idea is to use a greedy methods. We use a hashmap to store the number of each task. We shall fill the gap (cool down) as much as possible. Therefore, we need to fill the gap task one by one, until we cannot fill any task into the slot (or we comes to slot that can repeat the task before). Then I wrote a figure for this, I suddenly find a way that, we can use a heap to record the count. When we add a task, we remove it from the heap, after k slot, we put it back the heap. in this case, we are using a logn*N time to solve this problem.

The std use a more clever way to achieve the same way as above. When using a heap, actually we do not need to care about who is the biggest. The only thing we need to do, we need pop out n elements from the heap, and decrease the count of each element. If the count is not zero, we put it back to the heap. If the count is zero, we do not need to put it back to the heap. In this way, we can achieve the same result as above. And if the elements in the heap is less than n, we can just accumulate the answer by n - heap.size().