在O(n)(线性时间)中列出列表中的最大,第二大,最小和第二最小值

时间:2018-01-10 19:01:56

标签: python

l = [5, 4, 3, 2, 1, 100, 69]
largest = l[0]
smallest = l[0]
seclargest = 0
secsmallest = 0
a = len(l)
b = a - 1
for i in range(a):
    if l[i] > largest:
        seclargest=largest
        if b == i:
            print(seclargest)
        largest = l[i]
    if l[i] < smallest:
        if b>i:
            secsmallest = smallest
        smallest = l[i]

print(largest)
print(seclargest)
print(smallest)
print(secsmallest)
请帮忙。此代码仅打印正确的最小和第二小,但不打印最大和第二大值。

1 个答案:

答案 0 :(得分:0)

如果你想在线性时间内进行(一个for循环),你可以按如下方式修改你的代码:

l = [5, 4, 3, 2, 1, 100, 69]
largest = -1e10  # initialize to large negative number
smallest = 1e10  # initialize to large positive number
seclargest = -1e9 
secsmallest = 1e9
for x in l:
    if x > largest:
        seclargest=largest
        largest = x
    elif x > seclargest:
        seclargest = x
    elif x < smallest:
        secsmallest = smallest
        smallest = x
    elif x < secsmallest:
        secsmallest = x

print(largest)
print(seclargest)
print(smallest)
print(secsmallest)

哪个输出:

100
69
1
2

你非常接近。您只需要为数字小于最大值的情况添加一个条件,但是大于第二个最小值和第二个最小值的类似条件。

此外,您只需使用for x in l遍历列表,就无需迭代索引。