LeetCode 170. 两数之和 III - 数据结构设计(哈希map)
生活随笔
收集整理的这篇文章主要介绍了
LeetCode 170. 两数之和 III - 数据结构设计(哈希map)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
文章目录
- 1. 题目
- 2. 解题
1. 题目
设计并实现一个 TwoSum 的类,使该类需要支持 add 和 find 的操作。
add 操作 - 对内部数据结构增加一个数。
find 操作 - 寻找内部数据结构中是否存在一对整数,使得两数之和与给定的数相等。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-iii-data-structure-design
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
class TwoSum {unordered_map<int,int> m; public:/** Initialize your data structure here. */TwoSum() {}/** Add the number to an internal data structure.. */void add(int number) {m[number]++;}/** Find if there exists any pair of numbers which sum is equal to the value. */bool find(int value) {for(auto it = m.begin(); it != m.end(); ++it){if((it->first*2 == value && it->second>=2)||(it->first*2 != value && m.find(value-it->first)!=m.end()))return true;}return false;} };388 ms 22.6 MB
长按或扫码关注我的公众号,一起加油、一起学习进步!
总结
以上是生活随笔为你收集整理的LeetCode 170. 两数之和 III - 数据结构设计(哈希map)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Feature Engineering
- 下一篇: LeetCode 466. 统计重复个数