Find top N elements in an Array

前端 未结 12 1276
南笙
南笙 2020-11-28 06:18

What would be the best solution to find top N (say 10) elements in an unordered list (of say 100).

The solution which came in my head was to 1. sort it using quick s

12条回答
  •  没有蜡笔的小新
    2020-11-28 06:55

    Yes, you can do it in O(n) by just keeping a (sorted) running list of the top N. You can sort the running list using the regular library functions or a sorting network. E.g. a simple demo using 3, and showing which elements in the running list change each iteration.

    5 2 8 7 9

    i = 0
    top[0] <= 5
    
    i = 1
    top[1] <= 2
    
    i = 2
    top[2] <= top[1] (2)
    top[1] <= top[0] (5)
    top[0] <= 8
    
    i = 3
    top[2] <= top[1] (5)
    top[1] <= 7
    
    i = 4
    top[2] <= top[1] (7)
    top[1] <= top[0] (8)
    top[0] <= 9
    

提交回复
热议问题