[leetcode] 170. Two Sum III - Data structure design 解题报告

38 篇文章 0 订阅

题目链接:https://leetcode.com/problems/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

思路: 用hash表将元素都保存起来,然后查找的时候遍历hash表, 看当前元素与要查找的元素是否存在hash表中.

本题一个主要的问题就是有可能有重复元素, 即如果要查找的值如6, 可能由3+3构成, 这样如果你只有一个3是无法构成6的, 因此要对元素的个数进行记录并判断.

代码如下:

class TwoSum {
public:

    // 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 val: hash)
	    {
	        if(value!=2*val.first && hash.count(value-val.first))
	            return true;
	        if(value==2*val.first && val.second > 1)
	            return true;
	    }
	    return false;
	}
private:
    unordered_map<int, int> hash;
};


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值