- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtwo_sum.py
More file actions
Latest commit
36 lines (31 loc) · 843 Bytes
/
Copy pathtwo_sum.py
File metadata and controls
36 lines (31 loc) · 843 Bytes
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
"""
Two sum
"""
# Leetcode: https://leetcode.com/problems/two-sum/
#Brute force O(N^2)
deftwoSum(nums, target):
#bruteforce solution
foriinrange(len(nums)):
forjinrange(i+1, len(nums)):
val=target-nums[i]
ifnums[j] ==val:
return [i,j]
# Optimized code O(N)
deftwoSum(nums, target):
#Using a dictionary O(N)
seen= {}
foriinrange(len(nums)):
complement=target-nums[i]
ifcomplementinseen:
return [seen[complement], i]
seen[nums[i]] =i
# Using HashMap O(N)
deftwo_sum(nums, target):
prevMap= {} #key:valye pair
fori, ninenumerate(nums):
diff=target-n
ifdiffinprevMap:
return [prevMap[diff], i]
prevMap[n] =i
return []
print(two_sum([2,7,11,15],9))