|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * k largest(or smallest) elements in an array |
| 5 | + * |
| 6 | + * Tags: Array, Sort, Heap |
| 7 | + */ |
| 8 | +class KthLargest { |
| 9 | + public static void main(String[] args) { |
| 10 | + KthLargest K = new KthLargest(); |
| 11 | + // int[] A = { 1, 3, 5, 2, 4, 6 }; |
| 12 | + int[] A = {1, 23, 12, 9, 30, 2, 50}; |
| 13 | + for (int k = 1; k <= A.length; k++) { |
| 14 | + // System.out.println(K.findKthLargest(A, k)); |
| 15 | + System.out.println(K.findKthLargestB(A, k)); |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * Priority Queue |
| 21 | + * O(n) + k * O(logn) |
| 22 | + */ |
| 23 | + public int findKthLargest(int[] A, int k) { |
| 24 | + if (k <= 0 || k > A.length) return -1; |
| 25 | + Queue<Integer> q = new PriorityQueue<Integer>(A.length, Collections.reverseOrder()); |
| 26 | + for (int n : A) q.add(n); |
| 27 | + int res = 0; |
| 28 | + for (int i = 0; i < k; i++) res = q.poll(); |
| 29 | + return res; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * QuickSelect |
| 34 | + * Use partition algorithm in Quick Sort |
| 35 | + */ |
| 36 | + public int findKthLargestB(int[] A, int k) { |
| 37 | + if (k <= 0 || k > A.length) return -1; |
| 38 | + |
| 39 | + int l = 0; // initialize |
| 40 | + int r = A.length - 1; |
| 41 | + int index; |
| 42 | + |
| 43 | + while (l < r) { |
| 44 | + index = partition(A, l, r); |
| 45 | + if (index > k - 1) { |
| 46 | + r = index - 1; |
| 47 | + } else if (index < k - 1) { |
| 48 | + l = index + 1; |
| 49 | + } else { |
| 50 | + return A[index]; |
| 51 | + } |
| 52 | + } |
| 53 | + return A[l]; |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Choose mid value as pivot |
| 58 | + * Move two pointers |
| 59 | + * Swap and move on |
| 60 | + * Return left pointer |
| 61 | + */ |
| 62 | + private static int partition(int[] a, int left, int right) { |
| 63 | + int pivot = a[left + (right - left) / 2]; |
| 64 | + while(left <= right) { |
| 65 | + while(a[left] > pivot) left++; |
| 66 | + while(a[right] < pivot) right--; |
| 67 | + if (left <= right) { |
| 68 | + int temp = a[left]; |
| 69 | + a[left] = a[right]; |
| 70 | + a[right] = temp; |
| 71 | + left++; |
| 72 | + right--; |
| 73 | + } |
| 74 | + } |
| 75 | + return left; |
| 76 | + } |
| 77 | +} |
0 commit comments