educative.io

Educative

I think the following solution fits better in to the subject of this topic

public static List<Integer> findClosestElements(int[] arr, int K, Integer X) {
    if(arr == null || arr.length == 0 || K <= 0) {
      return Collections.emptyList();
    }

    Queue<Integer> q = 
      new PriorityQueue<>((a, b) -> Math.abs(arr[b] - X) - Math.abs(arr[a] - X));
    Queue<Integer> qRes = new PriorityQueue<>();
    for(int i = 0; i < arr.length; i++) {
      if(q.size() < K) {
        q.offer(i);
      }
      else if(Math.abs(arr[q.peek()] - X) > Math.abs(arr[i] - X) ) {
        q.poll();
        q.offer(i);
      }
    }

    while(!q.isEmpty()) {
      qRes.offer(arr[q.poll()]);
    }

    List<Integer> res = new ArrayList<>();
    while(!qRes.isEmpty()) {
       res.add(qRes.poll());
     }

     return res;
  }

Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5474975244877824

Hey @Peter_Litvak!
Kudos to you for such a good approach! We really appreciate learners who deep dive and ponder over the provided solutions and suggest different solutions :slightly_smiling_face:.