Problem : https://leetcode.com/problems/two-sum-iii-data-structure-design/
M = Value - N. Use hash table to find whether M exists when given Value and N.
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.seen = {}
self.memo = set()
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
if number in self.seen:
self.seen[number] += 1
else:
self.seen[number] = 1
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
if value in self.memo: return True
for n in self.seen.keys():
if value - n == n:
if self.seen.get(n, 0) >= 2:
self.memo.add(value)
return True
elif self.seen.get(value - n, 0) > 0:
self.memo.add(value)
return True
return False
No comments:
Post a Comment