设计并实现TwoSum类。它应该支持以下操作:添加和查找。
add-将数字添加到内部数据结构中。
find-查找是否存在任何一对数字,其总和等于该值。
Input:add(1); add(3); add(5);
Output: find(4) -> true
find(7) -> false
在初始化和添加数字的时候都没什么特殊,主要是find,首先想到了把add的数字从小到大排序之后用167题的方法
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums=[]
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
self.nums.append(number)
self.nums.sort()
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
nums=self.nums
l=0
r=len(nums)-1
while l<r:
s=nums[l]+nums[r]
if s==value:
return True
elif s<value:
l+=1
elif s>value:
r-=1
else:
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)
然后发现这个运行时间太久了,于是有了第二个方案,初始化一个字典,key为存的数,value为数出现的次数
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums={} #初始化字典
self.min=float('inf') #正无穷
self.max=float('-inf') #负无穷
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
if number not in self.nums: #设置value值
self.nums[number]=0
self.nums[number]+=1
if number>self.max: #最大最小值
self.max=number
if number<self.min:
self.min=number
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
if value>2*self.max or value<self.min*2:
return False #因为两个数相加,当value大于两个最大值时不存在
for i in self.nums: #遍历字典里面的key
val=value-i
if val!=i:
if val in self.nums:
return True
else:
if self.nums[val]>1:
return True
return False
这次运行速度快了很多