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

后端 未结 15 755
心在旅途
心在旅途 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:20

    The second highest item is a fairly simple case, but for the kth highest item what you want is a selection algorithm. That page is pretty thorough so it's probably best just to read that.

    0 讨论(0)
  • 2020-12-13 18:25

    This will work, but I don't know if you want to retain the items in the list:

    max1 = max(myList)
    myList.remove(max1)
    max2 = max(myList)
    

    If you do, you can do this:

    max1 = max(myList)
    idx1 = myList.index(max1)
    myList.pop(idx1)
    
    max2 = max(myList)
    myList.insert(idx1,max1)
    
    0 讨论(0)
  • 2020-12-13 18:25

    Another solution that uses only base Python functions can be seen below:

    >>> largest = max(lst)
    >>> maxIndex = lst.index(largest)
    >>> secondLargest = max(max(lst[:maxIndex]), max(lst[maxIndex+1:]))
    

    If we split a list around its largest number, we know that the second largest number is either in the left half or the right half. So, we can trivially find the second largest number by simply finding the larger of the largest number in the left and right half of the list.

    It's trivial to show this is O(n) time and O(1) space. We traverse the list once to find the largest element, then again to find the second largest. We only store the largest values themselves and the index of the largest value.

    0 讨论(0)
  • 2020-12-13 18:27

    You iterate over the list, maintaining variables that contain the value of the highest and the second highest item encountered thus far. Each new item that is encountered will replace whichever of the two the new item is higher than (if any).

    0 讨论(0)
  • 2020-12-13 18:28

    Iterating through the entire list is the only way to do it without sorting.

    0 讨论(0)
  • 2020-12-13 18:30

    Sort the list, and if list is not null, extract last two element

    >>> a=[0,6,8,5,10,5]
    >>> a.sort()
    >>> a
    [0, 5, 5, 6, 8, 10]
    >>> if a:
    ...  print a[-1],a[-2]
    ... 
    10 8
    

    Simple and most efficient:)

    Now if sorting is not required, find max, remove max, find max again

    >>> a=[0,6,8,5,10,5]
    >>> max(a)
    10
    >>> a.remove(max(a))
    >>> max(a)
    8
    >>> 
    

    Of course, you will lose the original list but you can create a temporary list as well.

    0 讨论(0)
提交回复
热议问题