-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.py
29 lines (25 loc) · 999 Bytes
/
Solution.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
from typing import List
class Solution(object):
# brute force
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if (nums[i] + nums[j]) == target:
return [i, j]
# mistaken attempt, only for orderly array
def twoSum2(self, nums: List[int], target: int) -> List[int]:
for left in range(len(nums)):
for right in range(len(nums) - 1, left, -1):
if nums[left] + nums[right] > target:
continue
elif nums[left] + nums[right] < target:
break
else:
return [left, right]
def twoSum3(self, nums: List[int], target: int) -> List[int]:
map = {}
for index, cur in enumerate(nums):
expect = target - cur
if expect in map:
return [index, map[expect]]
map[cur] = index