Hi,
why not simply searching for the kth smallest number like this:
public static int findKthSmallestNumber(int[] nums, int k) {
Queue<Integer> q = new PriorityQueue<Integer>((a, b) -> b - a);
for (int i : nums) {
q.offer(i);
if (q.size() > k) {
q.poll();
}
}
return q.poll();
}
It is much simpler and uses O(k) space.
Thanks
Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Kth Smallest Number (easy) - Grokking the Coding Interview: Patterns for Coding Questions