|
| 1 | +package com.cunningdj.grokJava; |
| 2 | + |
| 3 | +import java.util.Comparator; |
| 4 | +import java.util.PriorityQueue; |
| 5 | + |
| 6 | +public class GrokkingTwoHeaps { |
| 7 | + public static void main(String[] args) { |
| 8 | + Tester tester = new Tester(); |
| 9 | + String testTitle = ""; |
| 10 | + |
| 11 | + // KTH_LARGEST |
| 12 | + testTitle = "KTH_LARGEST"; |
| 13 | + // Sorted ascending |
| 14 | + tester.intEquals(5, kthLargest(1, new int[]{1,2,3,4,5}), testTitle); |
| 15 | + tester.intEquals(1, kthLargest(5, new int[]{1,2,3,4,5}), testTitle); |
| 16 | + tester.intEquals(3, kthLargest(3, new int[]{1,2,3,4,5}), testTitle); |
| 17 | + // Sorted descending |
| 18 | + tester.intEquals(5, kthLargest(1, new int[]{5,4,3,2,1}), testTitle); |
| 19 | + tester.intEquals(1, kthLargest(5, new int[]{5,4,3,2,1}), testTitle); |
| 20 | + tester.intEquals(3, kthLargest(3, new int[]{5,4,3,2,1}), testTitle); |
| 21 | + // Unsorted |
| 22 | + tester.intEquals(5, kthLargest(1, new int[]{1,5,3,4,2}), testTitle); |
| 23 | + tester.intEquals(1, kthLargest(5, new int[]{1,5,3,4,2}), testTitle); |
| 24 | + tester.intEquals(3, kthLargest(3, new int[]{1,5,3,4,2}), testTitle); |
| 25 | + } |
| 26 | + |
| 27 | + public static int kthLargest(int k, int[] nums) { |
| 28 | + int n = nums.length; |
| 29 | + PriorityQueue<Integer> heap; |
| 30 | + boolean checkingLargest = k < n / 2; |
| 31 | + // This optimization will allow the complexity to always be O(log(n/2)) or less |
| 32 | + if (checkingLargest) { |
| 33 | + // Use Min Heap (Kth LARGEST) |
| 34 | + heap = new PriorityQueue<>(k); |
| 35 | + } else { |
| 36 | + // Use Max Heap (Kth SMALLEST - convert k to the "smallest" equivalent number) |
| 37 | + k = n - k + 1; |
| 38 | + // Comparator reversed will keep the LARGEST element at the top instead of the smallest |
| 39 | + heap = new PriorityQueue<>(k, Comparator.reverseOrder()); |
| 40 | + } |
| 41 | + |
| 42 | + int i = 0; |
| 43 | + while (i < k) { |
| 44 | + heap.add(nums[i]); |
| 45 | + ++i; |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | + // Could also separate the min/max into two separate while loops for further optimization, but |
| 50 | + // putting both checks in one while loop here to demonstrate the shared code |
| 51 | + while (i < n) { |
| 52 | + if (// Min Heap: pushing LARGEST on |
| 53 | + (checkingLargest && nums[i] > heap.peek()) || |
| 54 | + // Max Heap: Pushing SMALLEST on |
| 55 | + (!checkingLargest && nums[i] < heap.peek())) |
| 56 | + { |
| 57 | + heap.poll(); |
| 58 | + heap.add(nums[i]); |
| 59 | + } |
| 60 | + ++i; |
| 61 | + } |
| 62 | + |
| 63 | + return heap.peek(); |
| 64 | + } |
| 65 | +} |
0 commit comments