Finding the first n largest elements in an array

后端 未结 8 436
不思量自难忘°
不思量自难忘° 2020-12-09 04:42

I have got an array containing unique elements. I need to find out the first n largest elements in the array in the least complexity possible. The solution that I could thin

8条回答
  •  無奈伤痛
    2020-12-09 05:31

    The usual trick to select the n largest elements is to maintain a min-priority queue.

    • Unconditionnally insert into the queue the n first elements
    • For each remaining element x, insert x if it is greater than the least element of the queue (O(log n) operation), and remove the least element (O(log n)).
    • When done, the priority queue contains n elements, which are the n largest elements of the original array.

    Total complexity: O(N log n) where N is the total number of elements in the array.

    I leave to you as an exercise the implementation details (first step is to learn about priority queues, and implement one).

提交回复
热议问题