首页 > 解决方案 > 最快(最少执行时间)的方法来获取 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)

标签: pythonarraysalgorithmdata-structuresminmax

解决方案


基本上,您找到最小值和最大值的方法根本没有任何重大影响。此外,与寻找最小值和最大值的正常方法相比,它需要更多的时间来执行。(即迭代两次并交换相邻元素,如果前一个和后一个较小或较大,然后直接访问第一个和最后一个元素以分别获取最小值和最大值。)

为了说明为什么您的代码不如传统方法高效,我执行了您的代码 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

推荐阅读