Retrieve the two highest item from a list containing 100,000 integers

后端 未结 15 752
心在旅途
心在旅途 2020-12-13 17:55

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?

15条回答
  •  醉梦人生
    2020-12-13 18:36

    The best time you can expect is linear, since you have to at least look through all the elements.

    Here is my pseudocode to solve the problem:

    //assume list has at least 2 elements
    (max, nextMax) = if (list[0] > list[1])
                     then (list[0], list[1])
                     else (list[1], list[0])
    
    for (2 <= i < length) {
        (max, nextMax) = if       (max < list[i])     => (list[i], max)
                         elseif   (nextMax < list[i]) => (max, list[i])
                         else     (no change)         => (max, nextMax)
    }
    
    return (max, nextMax)
    

提交回复
热议问题