Leetcode 刷题 - 170 - Two Sum III - Data structure design

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


class TwoSum(object):

    def __init__(self):
        """
        initialize your data structure here
        """

    def add(self, number):
        """
        Add the number to an internal data structure.
        :rtype: nothing
        """

    def find(self, value):
        """
        Find if there exists any pair of numbers which sum is equal to the value.
        :type value: int
        :rtype: bool
        """

# Your TwoSum object will be instantiated and called as such:
# twoSum = TwoSum()
# twoSum.add(number)
# twoSum.find(value)


题目如上。根据题意,就是构建一个数据结构,能够完成add添加数字,find找到two sum。

我的思路是,因为有find,所以直接上来就觉得应该用hashtable之类的构建。对于python,练习下来觉得就是字典dictionary最好。


add没什么好说的,key有就+1,没有就添加。

<span style="white-space:pre">	</span>if number not in dic:
            dic[number] = 1
        else:
            dic[number] += 1

对于find,因为是two sum,给了我们一个target值,那么就target - dic[i], 判断结果是不是在dic中,在就是True,否则就是False。

Target - dic[i] == dic[j]

考虑到可能有重复的数字,除了上面的情况,还有重复数字的情况。

Target - dic[i] == dic[i]

所以,合并一下,就是数字相同的时候,判断是否key数字的value大于1。不同的时候,就判断是否剩余值也在key中。

value - num in dic and (value - num != num or dic[num] > 1):


class TwoSum(object):

    def __init__(self):
        self.dic = {}

    def add(self, number):
        if number not in self.dic:
            self.dic[number] = 1
        else:
            self.dic[number] += 1

    def find(self, value):
        dic = self.dic
        for num in dic:
            if value - num in dic and (value - num != num or dic[num] > 1):
                return True
        return False











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值