Retrieving the top 100 numbers from one hundred million of numbers

前端 未结 12 2146
北荒
北荒 2020-11-30 19:36

One of my friend has been asked with a question

Retrieving the max top 100 numbers from one hundred million of numbers

in a rece

12条回答
  •  温柔的废话
    2020-11-30 20:08

    There's no reason to sort the whole list. This should be doable in O(n) time. In pseudocode:

    List top = new List
    
    for each num in entireList
        for i = 0 to top.Length
            if num > top[i] then
                top.InsertBefore(num, i)
                if top.Length > 100 then
                    top.Remove(top.Length - 1)
                end if
                exit for
            else
                if i = top.Length - 1 and i < 100 then
                    top.Add(num)
                end if
            end if
        next
    next
    

提交回复
热议问题