-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathtwo_sum.py
More file actions
49 lines (42 loc) · 1.46 KB
/
two_sum.py
File metadata and controls
49 lines (42 loc) · 1.46 KB
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
# coding: utf-8
"""
https://leetcode.com/problems/two-sum/
"""
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Is there duplicates in `nums`?
for i, num1 in enumerate(nums):
for j, num2 in enumerate(nums[i + 1:]):
if num1 + num2 == target:
real_index = j + i + 1
return [i, real_index]
class Solution2:
def twoSum(self, nums: List[int], target: int) -> List[int]:
mapping = {
# num: index
}
for i, num in enumerate(nums):
mapping[num] = i
for i, num in enumerate(nums):
another = target - num
try:
# We cannot use the same element twice, so both returned indexes must be distinct.
another_i = mapping[another]
if another_i == i:
continue
else:
return [i, another_i]
except KeyError:
continue
class Solution3:
def twoSum(self, nums: List[int], target: int) -> List[int]:
mapping = {
# num: index
}
for i, num in enumerate(nums):
another = target - num
another_i = mapping.get(another)
if another_i is not None: # NOTE: The index of another might be 0, so we cannot use `if another_i:`.
return [another_i, i]
mapping[num] = i