LeetCode-Python-170. 两数之和 III - 数据结构设计

博客介绍设计并实现TwoSum类,该类需支持add和find操作。add用于增加数,find用于寻找内部数据结构中是否存在两数之和等于给定数。示例展示了操作结果,思路是用哈希表记录每个数出现次数,同时要注意特殊情况处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计并实现一个 TwoSum 的类,使该类需要支持 add 和 find 的操作。

add 操作 -  对内部数据结构增加一个数。
find 操作 - 寻找内部数据结构中是否存在一对整数,使得两数之和与给定的数相等。

示例 1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> false
示例 2:

add(3); add(1); add(2);
find(3) -> true
find(6) -> false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-iii-data-structure-design
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

用哈希表实现。用一个哈希表记录每个数出现的次数, key是数字,val是出现的次数。

注意处理key * 2 = 要找的数时的特殊情况。

class TwoSum(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import defaultdict
        self.dict = defaultdict(int)
        

    def add(self, number):
        """
        Add the number to an internal data structure..
        :type number: int
        :rtype: None
        """
        self.dict[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, val in self.dict.items():
            if value - key in self.dict:
                if key * 2 == value and self.dict[key] > 1:
                    return True
                elif key * 2 != value:
                    return True
        return False

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值