Last active
October 11, 2021 11:46
-
-
Save Asutosh11/d956c27a3572162c3567d37719a74725 to your computer and use it in GitHub Desktop.
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
fun main(args: Array<String>) { | |
val k = 3 | |
// k smallest element | |
// by default a PriorityQueue makes a min heap | |
val priorityQueue: PriorityQueue<Int> = PriorityQueue<Int>() | |
priorityQueue.add(20) | |
priorityQueue.add(4) | |
priorityQueue.add(1) | |
priorityQueue.add(35) | |
priorityQueue.add(66) | |
priorityQueue.add(12) | |
for(i in 1 until k+1){ | |
val smallest = priorityQueue.peek() | |
priorityQueue.poll() | |
if(i == k){ | |
println("Kth smallest: " + smallest) | |
} | |
} | |
// k largest element | |
// by default a PriorityQueue makes a min heap, | |
// reverse the order to make it a max heap | |
val priorityQueueReverse: PriorityQueue<Int> = | |
PriorityQueue<Int>(Collections.reverseOrder()) | |
priorityQueueReverse.add(20) | |
priorityQueueReverse.add(4) | |
priorityQueueReverse.add(1) | |
priorityQueueReverse.add(35) | |
priorityQueueReverse.add(66) | |
priorityQueueReverse.add(12) | |
for(i in 1 until k+1){ | |
val largest = priorityQueueReverse.peek() | |
priorityQueueReverse.poll() | |
if(i == k){ | |
println("Kth largest: " + largest) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment