簡體   English   中英

找到兩個數字之和的最有效方法

[英]most efficient way to find a sum of two numbers

我正在研究一個問題:給定一個任意列表,在這種情況下它是[9,15,1,4,2,3,6],找到任何兩個數字將總和給定的結果(在這種情況下為10) 。 最有效的方法是什么? 我的解決方案是大O符號n 2 ,即使我已經過濾和排序數字,我相信有一種方法可以更有效地做到這一點。 提前致謝

myList  = [9,15,1,4,2,3,6]
myList.sort()
result = 10
myList = filter(lambda x:x < result,myList)
total = 0
for i in myList:
    total = total + 1
    for j in myList[total:]:
        if i + j == result:
            print i,j
            break

O(n log n)解決方案

排序列表。 對於每個數字x ,在列表中二進制搜索 S - x

O(n)解決方案

對於每個數字x ,查看哈希表中是否有S - x x添加到哈希表中

請注意,如果您的數字非常小,則哈希表可以是一個簡單的數組,其中h[i] = true if i exists in the hash table and false otherwise

使用字典為此和列表中的每個項目查找total_required - item字典中的total_required - item 我在這里使用了collections.Counter ,因為如果total_required - item等於列表中的當前項,則set可能會失敗。 總體復雜度為O(N)

>>> from collections import Counter
>>> def find_nums(total, seq):
    c = Counter(seq)
    for x in seq:
        rem = total - x
        if rem in c:
            if rem == x and c[rem] > 1:
                return x, rem
            elif rem != x:
                return x, rem
...         
>>> find_nums(2, [1, 1])
(1, 1)
>>> find_nums(2, [1])
>>> find_nums(24, [9,15,1,4,2,3,6])
(9, 15)
>>> find_nums(9, [9,15,1,4,2,3,6])
(3, 6)

我認為,這個解決方案可行....

list  = [9,15,1,4,2,3,6]
result = 10
list.sort()
list = filter(lambda x:x < result,list)
myMap = {}

for i in list:
    if i in myMap:
        print myMap[i], i
        break
    myMap[result - i] = i

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM