Finding the first n largest elements in an array

后端 未结 8 462
不思量自难忘°
不思量自难忘° 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:20

    You can use a Priority Queue using Heap (maxHeap) to solve this. Perform heap n times to get the first n largest elements. Each Heap operation takes O(log N) time, so N heap operations would result in O(N log N) time.

提交回复
热议问题