Skip to content

Commit 388765f

Browse files
committed
Add solution for Two Sum
1 parent 5744078 commit 388765f

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

two-sum/gcount85.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
- Approach:
3+
Make a dictionary.
4+
The key is difference from target and the value is its index,
5+
then iterate the number array and with its value, find the key in the dictionary.
6+
- Time Complexity: O(2N) => O(N)
7+
- Space complexity: O(N)
8+
"""
9+
10+
11+
class Solution:
12+
def twoSum(self, nums: List[int], target: int) -> List[int]:
13+
num_dic = {}
14+
for i, v in enumerate(nums): # O(N)
15+
num_dic[target - v] = i
16+
17+
for i, v in enumerate(nums): # O(N)
18+
if v in num_dic and num_dic[v] != i:
19+
return [num_dic[v], i]

0 commit comments

Comments
 (0)