|
| 1 | +package Top_K_Elements; |
| 2 | + |
| 3 | +// Problem Statement: 'K' Closest Numbers (medium) |
| 4 | +// LeetCode Question: 658. Find K Closest Elements |
| 5 | + |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.Collections; |
| 8 | +import java.util.List; |
| 9 | +import java.util.PriorityQueue; |
| 10 | + |
| 11 | +public class Problem_8_K_Closest_Number { |
| 12 | + |
| 13 | + class Entry { |
| 14 | + int key; |
| 15 | + int value; |
| 16 | + |
| 17 | + public Entry(int key, int value) { |
| 18 | + this.key = key; |
| 19 | + this.value = value; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + public List<Integer> findClosestElements(int[] arr, int K, Integer X) { |
| 24 | + int index = binarySearch(arr, X); |
| 25 | + int low = index - K, high = index + K; |
| 26 | + low = Math.max(low, 0); // 'low' should not be less than zero |
| 27 | + // 'high' should not be greater the size of the array |
| 28 | + high = Math.min(high, arr.length - 1); |
| 29 | + |
| 30 | + PriorityQueue<Entry> minHeap = new PriorityQueue<>((n1, n2) -> n1.key - n2.key); |
| 31 | + // add all candidate elements to the min heap, sorted by their absolute difference |
| 32 | + // from 'X' |
| 33 | + for (int i = low; i <= high; i++) |
| 34 | + minHeap.add(new Entry(Math.abs(arr[i] - X), i)); |
| 35 | + |
| 36 | + // we need the top 'K' elements having smallest difference from 'X' |
| 37 | + List<Integer> result = new ArrayList<>(); |
| 38 | + for (int i = 0; i < K; i++) |
| 39 | + result.add(arr[minHeap.poll().value]); |
| 40 | + |
| 41 | + Collections.sort(result); |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + private static int binarySearch(int[] arr, int target) { |
| 46 | + int low = 0; |
| 47 | + int high = arr.length - 1; |
| 48 | + while (low <= high) { |
| 49 | + int mid = low + (high - low) / 2; |
| 50 | + if (arr[mid] == target) |
| 51 | + return mid; |
| 52 | + if (arr[mid] < target) { |
| 53 | + low = mid + 1; |
| 54 | + } else { |
| 55 | + high = mid - 1; |
| 56 | + } |
| 57 | + } |
| 58 | + if (low > 0) { |
| 59 | + return low - 1; |
| 60 | + } |
| 61 | + return low; |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments