-
Notifications
You must be signed in to change notification settings - Fork 0
/
-1_two-sum.py
40 lines (32 loc) · 946 Bytes
/
-1_two-sum.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
###############
# MY SOLUTION #
###############
def twoSum(nums, target):
counter = 0
while len(nums) > 0:
num = nums.pop(0)
for i in range(len(nums)):
if num + nums[i] == target:
return [counter, (counter+i+1)]
counter += 1
#######################
# Two-pass Hash Table #
#######################
def twoSum(nums, target):
hashmap = {}
for i in range(len(nums)):
hashmap[nums[i]] = i
for i in range(len(nums)):
complement = target - nums[i]
if complement in hashmap and hashmap[complement] != i:
return [i, hashmap[complement]]
#######################
# One-pass Hash Table #
#######################
def twoSum(nums, target):
hashmap = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement in hashmap:
return [i, hashmap[complement]]
hashmap[nums[i]] = i