[英]What is the most efficient way of doing square root of sum of square of two numbers?
[英]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
使用字典為此和列表中的每個項目查找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.