Two Sum III - Data structure design
Design and implement a TwoSum class. It should support the following operations:add
andfind
.
add
- Add the number to an internal data structure.
find
- Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
class TwoSum(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.table = dict()
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: void
"""
if not self.table.has_key(number):
self.table[number] = 1
else:
self.table[number] += 1
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
for k in self.table.keys():
if k == (value - k) and self.table[k] > 1:
return True
elif k != (value - k) and self.table.has_key(value - k):
return True
return False
Last updated
Was this helpful?