Description:
Design and implement a TwoSum class. It should support the following operations: add and find.
-
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.
Example
Example 1:
add(1); add(3); add(5);
find(4) // return true
find(7) // return false
Solutions:
From Two Sum II
class TwoSum:
def __init__(self,):
self.ls = []
self.sort = False
"""
@param number: An integer
@return: nothing
"""
def add(self, number):
# write your code here
self.ls.append(number)
self.sort = False
"""
@param value: An integer
@return: Find if there exists any pair of numbers which sum is equal to the value.
"""
def find(self, value):
# write your code here
if not self.sort:
self.ls.sort()
self.sort = True
l = 0
r = len(self.ls) - 1
while l < r:
if self.ls[l] + self.ls[r] < value:
l += 1
elif self.ls[l] + self.ls[r] > value:
r -= 1
else:
return True
return False
Total runtime 1130 ms
Your submission beats 10.00% Submissions!
From Two Sum I
from collections import defaultdict
class TwoSum:
def __init__(self,):
self.ls = []
self.dic = defaultdict(list)
"""
@param number: An integer
@return: nothing
"""
def add(self, number):
# write your code here
if len(self.dic[number]) < 2:
self.ls.append(number)
self.dic[number].append(len(self.ls))
"""
@param value: An integer
@return: Find if there exists any pair of numbers which sum is equal to the value.
"""
def find(self, value):
# write your code here
for n in self.ls:
if n*2 == value:
return len(self.dic[n]) == 2
elif (value-n) in self.dic:
return True
return False
Total runtime 822 ms
Your submission beats 56.40% Submissions!
from collections import defaultdict
class TwoSum:
def __init__(self,):
self.ls = []
self.dic = defaultdict(int)
"""
@param number: An integer
@return: nothing
"""
def add(self, number):
# write your code here
self.ls.append(number)
self.dic[number] += 1
"""
@param value: An integer
@return: Find if there exists any pair of numbers which sum is equal to the value.
"""
def find(self, value):
# write your code here
for n in self.ls:
if n*2 == value:
return self.dic[n] >= 2
elif (value-n) in self.dic:
return True
return False
Total runtime 670 ms
Your submission beats 96.80% Submissions!