Two Sum

題目

You are given a list of numbers, and a target number k. Return whether or not there are two numbers in the list that add up to k.code

Example:
Given [4, 7, 1 , -3, 2] and k = 5,
return true since 4 + 1 = 5.get

Try to do it in a single pass of the list.it

分析

使用一個字典儲存每個遍歷到的元素。
只需遍歷一次列表,對每一個元素判斷 k 減去它的差是否已經在字典中便可。class

時間複雜度 O(n).遍歷

代碼

def two_sum(list, k):
  d = {}
  for num in list:
    other = k - num
    if other in d:
      return True
    else:
      d[num] = 1

  return False

print two_sum([4,7,1,-3,2], 5)
# True
相關文章
相關標籤/搜索