Optimal algorithm for returning top k values from an array of length N

前端 未结 5 496
一个人的身影
一个人的身影 2020-11-27 03:22

I have an array of n floats, and I wish to return the top k (in my case n ~ 100, k ~ 10)

Is there a known optimal solution path for this problem?

Could some

5条回答
  •  日久生厌
    2020-11-27 04:03

    You can do this in O(n) by using a selection algorithm. Find the kth largest element with the partition algorithm, then all the elements after it will be larger than it, and those are your top k.

    If you need those top k in sorted order, you can then sort them in O(k log k).

提交回复
热议问题