Description

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

Bonus: Can you do this in one pass?


Solution: GoLang

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func twoSum(nums int[], target int) bool {
  _map = map[int]bool
  for i, v := range nums {
    ok, v := _map[v]; if ok {
      return True
    } else {
      _map[target - v] = true
    }
  }
  return false
}


Solution: Python3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def twoSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: bool
    """
    _map = dict()
    for i, v in enumerate(nums):
        if target - v in _map:
            return True
        else:
            _map[v] = i
    return False