用python求一个数组中最大的两个数
#迭代版1:
def findmax_two(L):
n=len(L)
if n=2:
return L[0],L[1]
if n>=3:
for i in range(n):
x1=0
if L[x1]<L[i]:
x1=i
return L[x1]
for x in range(0,i):
x2=0
if L[x2]<L[x]:
x2=x
return L[x2]
for y in range(i,n-1):
if x2<L[y]:
x2=y
return L[x2]
L=[33,23,24,36,44,67,99]
print(findmax_two(L))
#迭代版2
def find_two(L):
n=len(L)
x1=0
x2=1
if L[x1]<L[x2]:
X1=1
x2=0
for i in range(0,n):
if L[x2]<L[i]<L[x1]:
x2=i
if L[i]>L[x1]:
x2=x1
x1=i
if L[i]<L[x2]:
pass return L[x1],L[x2]
L=[12,23,4,56,76,98]
print(find_two(L))
#递归+分治:
def find_two(L):
n=len(L)
if n=1:
return L[0],L[0]
if n==2:
if L[0]<L[1]:
return L[1],L[0]
else:
return L[0],L[1] l1,l2=find_two(L[:n//2])
r1,r2=find_two(L[n//2:n])
if l1>r1:
if l2>r1:
return l1,l2
else:
return l1,r1
if l1<r1:
if l1<r2:
return r1,r2
else:
return r1,l1
L=[12,1,456,67,90,35,57,98]
print(find_two(L))
07-07
802
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-11
09-11