您不必对输入进行排序,并且此解决方案在 O(n) 中运行。由于您的问题说您不能使用内置函数,因此您可以使用它
alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
largest, larger = alist[0], alist[0]
for num in alist:
if num > largest:
largest, larger = num, largest
elif num > larger:
larger = num
print larger
输出
100
跟踪最大数字和第二大数字(larger
变量存储在代码中)。如果当前数大于largest
,则当前数变为largest
,largest
变为just larger
。
largest, larger = num, largest
是一个捷径
temp = largest
largest = num
larger = temp
编辑:根据评论中OP的要求,
def findLarge(myList):
largest, larger = myList[0], myList[0]
for num in myList:
if num > largest:
largest, larger = num, largest
elif num > larger:
larger = num
return largest, larger
alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
firstLargest, firstLarger = findLarge(alist[:len(alist)//2])
secondLargest, secondLarger = findLarge(alist[len(alist)//2:])
print sorted((firstLarger, firstLargest, secondLarger, secondLargest))[-2]