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. 统计重复个数