170. Two Sum III - Data structure design

本文介绍了一种名为TwoSum的数据结构设计与实现方法,该结构支持add和find操作。通过使用哈希表来存储数值及其出现次数,可以高效地查找是否存在两个数之和等于特定值。文中还详细讨论了实现过程中的易错点。

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

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.

Example 1:

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

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

方法1:

思路:

用hashmap,因为会有重复数字,需要计数。分为两种情况判断,是否和当前值不一样,如果一样,查询差值是否存在;如果一样,必须要求差值的数量>1。

易错点

  1. 用修改hash值的方法会出错
class TwoSum {
public:
    /** Initialize your data structure here. */
    TwoSum() {
        
    }
    
    /** Add the number to an internal data structure.. */
    void add(int number) {
        ++hash[number];
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
        for (auto & item: hash){
            int t = value - item.first;
            if (t != item.first && hash.count(t)) {
                return true;
            }
            else if (t == item.first && hash[t] > 1){
                return true;
            }
        }
        return false;
    }
private:
    unordered_map<int, int> hash;
};

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * bool param_2 = obj.find(value);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值