-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwosum.py
56 lines (43 loc) · 1.15 KB
/
twosum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
Task:
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
>>> two_sum([3, 2, 4], 6)
[1, 2]
>>> two_sum([2, 7, 11, 15], 9)
[0, 1]
>>> two_sum([0, 2, 3, 0], 0)
[0, 3]
"""
# Solution 1: double loop
def two_sum(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return None
# Solution 2: two-pass hash table
def two_sum(nums, target):
map_ = {}
# build a {element: index} map
for i, num in enumerate(nums):
map_[num] = i
for j, num in enumerate(nums):
complement = target - num
if complement in map_ and \
map_[complement] != j:
return [j, map_[complement]]
return None
# Solution 3: one-pass hash table
def two_sum(nums, target):
map_ = {}
# build map while iter
for i, num in enumerate(nums):
complement = target - num
if complement in map_:
return [map_[complement], i]
map_[num] = i
return None
if __name__ == '__main__':
import doctest
doctest.testmod()