Untitled
import java.util.*; public class KClosestElements { public List<Integer> findClosestElements(int[] arr, int k, int x) { // Max-heap to store (distance, value) pairs PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> { if (b[0] != a[0]) { return b[0] - a[0]; // Compare by distance } else { return b[1] - a[1]; // If distances are the same, compare values } }); // Add elements to the heap for (int num : arr) { int distance = Math.abs(num - x); maxHeap.offer(new int[]{distance, num}); // Remove the element with the largest distance if heap size exceeds k if (maxHeap.size() > k) { maxHeap.poll(); } } // Extract elements from the heap and sort them List<Integer> result = new ArrayList<>(); while (!maxHeap.isEmpty()) { result.add(maxHeap.poll()[1]); } Collections.sort(result); // Sort the result in ascending order return result; } public static void main(String[] args) { KClosestElements solution = new KClosestElements(); // Example 1 int[] arr1 = {1, 2, 3, 4, 5}; System.out.println(solution.findClosestElements(arr1, 4, 3)); // Output: [1, 2, 3, 4] // Example 2 int[] arr2 = {1, 1, 2, 3, 4, 5}; System.out.println(solution.findClosestElements(arr2, 4, -1)); // Output: [1, 1, 2, 3] } }
Leave a Comment