首页 > 技术文章 > Two Sum

new-start 2019-10-12 00:54 原文

题目

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.

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

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

分析

使用一个字典储存每一个遍历到的元素。
只需遍历一次列表,对每个元素判断 k 减去它的差是否已经在字典中即可。

时间复杂度 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

推荐阅读