最快(最少执行时间)的方法来获得int数组的max/min,除了range()和len()之外没有内置函数



我正在寻找一种更快,更少的执行时间方法来获得整数数组的最大和最小元素,这意味着我们需要对整数数组进行排序。除了range()和len()之外,没有使用任何像sort()这样的内置函数,并且只使用一个for或while循环,我无法弄清楚。

def getMinMax( a, n):
while 1 == 1:
run = False
for i in range(n):
if i < (n-1) and a[i] > a[i+1]:
run = True
if run:
for i in range(n):
if i < (n-1) and a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
else:
break
return a[0], a[i], a
A = [2, 167, 56, 3, 10000, 1]
min_elem, max_elem, sorted_array = getMinMax(A, len(A))
min_elem, max_elem, sorted_array

输出:

(1, 10000, [1, 2, 3, 56, 167, 10000])

与一个循环

def getMinMax( a, n):
min_elem = a[0]
max_elem = a[0]
for i in range(n):
if i < (n-1):
if a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
max_var, min_var = a[n-1], a[0]
return max_elem, min_elem
array = [3,123,200,4,500000,1]
getMinMax( array, len(array))

输出:

(500000, 3)

基本上,您查找最小值和最大值的方法根本没有任何主要影响。此外,它比查找最小和最大的普通方法花费更多的时间来执行。(即迭代两次并交换相邻元素,如果前一个和后一个较小或较大,然后直接访问第一个和最后一个元素以获得最小和最大值resp)

为了证明为什么你的代码不如传统方法高效,我将你的代码与我的传统代码执行了100000000次,次数相同,发现你的代码实际上比我的代码花费更多的时间!

import timeit
A = [3, 2, 1, 56, 10000, 167]
code1 = '''
def getMinMax( a, n):
while 1 == 1:
run = False
for i in range(n):
if i < (n-1) and a[i] > a[i+1]:
run = True
if run:
for i in range(n):
if i < (n-1) and a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
else:
break
print(a[i], a[0])
return a[i], a[0]
'''
code2 = '''
def min_max(A):
for i in range(len(A)):
for j in range(1, len(A)-1):
if A[j] > A[j+1]:
A[j],A[j+1] = A[j+1],A[j]
print(A[0], A[len(A)-1])
return A[0],A[len(A)-1]
'''
print(timeit.timeit(stmt=code1, number=100000000))
print(timeit.timeit(stmt=code2, number=100000000))

输出:

6.4907884000000005 #<-- your code's execution time after the 100000000th execution
5.600494200000001 #<-- my code's execution time after the 100000000th execution

我知道这很荒谬,但如果问问题的人真的不想使用min()和/或max()那么这也可以:

def getMinMax(A):
if A:
a = sorted(A)
return a[0], a[-1]
return None, None
l=[1,2,3,4,5]
print(max(l),min(l))

只使用min()和max()函数。
语法:
for min()

min(iterable_name)

为max ()

max(iterable_name)