LeetCode 170. 两数之和 III - 数据结构设计(哈希map)

    技术2022-08-10  75

    文章目录

    1. 题目2. 解题

    1. 题目

    设计并实现一个 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 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    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


    长按或扫码关注我的公众号,一起加油、一起学习进步!

    Processed: 0.024, SQL: 9