170. Two Sum III - Data structure design两个数加和III堆栈Python

设计并实现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

这次运行速度快了很多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值