我正在嘗試爲重複性面試問題做準備。給定一個數組,找到這些對以得到它們的總和爲k。我在這種情況下使用python字典而不是排序方法。代碼如下:使用python重複條目求和K使用
def sumToK(lst):
k = 16 # <- define the k here
d = {} # build a dictionary
# build the hashmap key = val of lst, value = i
for index, val in enumerate(lst):
d[val] = index
# find the key; if a key is in the dict, and not the same index as the current key
for i, val in enumerate(lst):
if (k-val) in d and d[k-val] != i:
print k-val, val
a = [1,4,45,6,10,12,3]
sumToK(a)
我正在以上述方式獲取重複值。我怎樣才能避免它?另外,如果數組包含重複的值,該怎麼辦?例如a = [1,4,45,6,10,12,4,8,8]謝謝。