forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#1658 from a93a/621
Create 621-Task-Scheduler.kt
- Loading branch information
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
class Solution { | ||
fun leastInterval(tasks: CharArray, n: Int): Int { | ||
if(n == 0) | ||
return tasks.size | ||
val hm = HashMap<Char,Int>() | ||
for(task in tasks) | ||
hm[task] = hm.getOrDefault(task, 0) + 1 | ||
val maxHeap = PriorityQueue<Int>(compareBy{-it}) | ||
for(count in hm.values) | ||
maxHeap.add(count) | ||
val q = ArrayDeque<Pair<Int,Int>>() // time, value | ||
var time = 0 | ||
while(!maxHeap.isEmpty() || !q.isEmpty()){ | ||
if(!maxHeap.isEmpty()){ | ||
var current = maxHeap.poll() | ||
current-- | ||
if(current > 0) | ||
q.add(Pair(time+n,current)) | ||
} | ||
if(!q.isEmpty()){ | ||
if(q.peek().first == time) | ||
maxHeap.add(q.poll().second) | ||
} | ||
time++ | ||
} | ||
return time | ||
} | ||
} |