Created
February 28, 2021 18:56
-
-
Save bijukunjummen/74cf20ede1ded55fca80dff7455d0980 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
import java.util.* | |
fun findNSmallestAndLargest(nums: List<Int>, n: Int): Pair<List<Int>, List<Int>> { | |
val minFirst: Comparator<Int> = Comparator.naturalOrder<Int>() | |
val maxFirst: Comparator<Int> = minFirst.reversed() | |
val minPq: PriorityQueue<Int> = PriorityQueue(minFirst) | |
val maxPq: PriorityQueue<Int> = PriorityQueue(maxFirst) | |
for (num in nums) { | |
checkAndAddIfSmallest(maxPq, n, num) | |
checkAndAddIfLargest(minPq, n, num) | |
} | |
return maxPq.toList() to minPq.toList() | |
} | |
private fun checkAndAddIfSmallest(maxPq: PriorityQueue<Int>, n: Int, num: Int) { | |
if (maxPq.size < n) { | |
maxPq.add(n) | |
} else if (num < maxPq.peek()) { | |
maxPq.poll() | |
maxPq.add(num) | |
} | |
} | |
private fun checkAndAddIfLargest(minPq: PriorityQueue<Int>, n: Int, num: Int) { | |
if (minPq.size < n) { | |
minPq.add(n) | |
} else if (num > minPq.peek()) { | |
minPq.poll() | |
minPq.add(num) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment