Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Without binary search also it can be done, Below is the efficient and easy solution

Jayant Kumar

Jun 15, 2023

  public static List<Integer> findClosestElements(int[] arr, int K, Integer X) {         PriorityQueue<Integer> maxHeap = new PriorityQueue<>(       (a1,a2) -> Math.abs(X-a2) - Math.abs(X-a1)     );     for(int n:arr){       maxHeap.add(n);       if(maxHeap.size()>K){         maxHeap.poll();       }     }     List<Integer> result = new ArrayList<>(maxHeap);     Collections.sort(result);     return result;   }

4

0

Comments
Comments
P
pranaykhanna2012 2 years ago

Nice one!

M
Mudassir Maredia2 years ago

I did the same way:

static List<Integer> kClosestNumberSelf(int[] arr, int K, int X) { PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for (int n : arr) { if (minHeap.size() == K) { if (Math.abs(X - n) < Math.abs(X - mi...

On this page