educative.io

Alternative Solution (Java). Is time comlexity correct?

Please take a look at my solution. Time complexity is O(Nlog(K) + K + Klog(K) ) = O(N*log(K)):

public static List findClosestElements(int[] arr, int K, Integer X) {
List result = new ArrayList();
// TODO: Write your code here
PriorityQueue pq = new PriorityQueue<>((a, b) → b.value - a.value);
for (int num: arr) {
Entry entry = new Entry(num, Math.abs(X - num));
pq.add(entry);
if (pq.size() > K) {
pq.poll();
}
}

for(int i = 0; i < K; i++) {
result.add(pq.poll().key);
}

Collections.sort(result);

return result;
}


Type your question above this line.

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