代码拉取完成,页面将自动刷新
# Time: O(n)
# Space: O(n)
# 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.
#
# For example,
# add(1); add(3); add(5);
# find(4) -> true
# find(7) -> false
from collections import defaultdict
class TwoSum(object):
def __init__(self):
"""
initialize your data structure here
"""
self.lookup = defaultdict(int)
def add(self, number):
"""
Add the number to an internal data structure.
:rtype: nothing
"""
self.lookup[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 key in self.lookup:
num = value - key
if num in self.lookup and (num != key or self.lookup[key] > 1):
return True
return False
if __name__ == "__main__":
Sol = TwoSum()
for i in (1, 3, 5):
Sol.add(i)
for i in (4, 7):
print Sol.find(i)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。