python - 最快(最少执行时间)的方法来获取 int 数组的最大值/最小值,除了 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)
解决方案
基本上,您找到最小值和最大值的方法根本没有任何重大影响。此外,与寻找最小值和最大值的正常方法相比,它需要更多的时间来执行。(即迭代两次并交换相邻元素,如果前一个和后一个较小或较大,然后直接访问第一个和最后一个元素以分别获取最小值和最大值。)
为了说明为什么您的代码不如传统方法高效,我执行了您的代码 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
推荐阅读
- phpmyadmin - 基于主机的身份验证中 '%' 的 phpMyAdmin 用户名通配符
- java - 如何使用流 API 过滤连续元素?
- ms-access - Microsoft Access 创建隐藏表单
- node.js - 尽管有字段,但MongoDB查询结果为空
- c# - 如何同时运行许多异步方法?
- javascript - 如何在 obj 中使用 for 循环?
- powerbi-embedded - 有人知道如何从 PowerBi Embeded v2 升级到 v3 吗?还是 v3 的教程?
- python - Python中for语句中的“aa”是做什么的?
- c# - 单击WPF Caliburn.Micro中的按钮时无法在DataGrid中全选
- python - 如何用 pandas 读出我的数据集?