class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.table = defaultdict(int)
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
self.table[number] += 1
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
for key in self.table:
target = value - key
if target == key and self.table[key] >= 2:
return True
if target != key and target in self.table:
return True
return False
雙指針
這一題也可以用雙指針來寫,不過要注意的是,我們需要檢查陣列的排序狀態。
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.arr = []
self.sorted = False
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
self.arr.append(number)
self.sorted = False
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
if self.sorted:
left = 0
right = len(self.arr) - 1
while left < right:
total = self.arr[left] + self.arr[right]
if total == value:
return True
elif total > value:
right -= 1
elif total < value:
left += 1
return False
else:
self.arr.sort()
self.sorted = True
return self.find(value)