170. Two Sum III - Data structure design【easy】
170. Two Sum III - Data structure design【easy】
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
?
這是一道收費題目,參考了grandyang的博客,感謝他!
?
解法一:
1 class TwoSum { 2 public: 3 void add(int number) { 4 ++m[number]; 5 } 6 bool find(int value) { 7 for (auto a : m) { 8 int t = value - a.first; 9 if ((t != a.first && m.count(t)) || (t == a.first && a.second > 1)) { 10 return true; 11 } 12 } 13 return false; 14 } 15 private: 16 unordered_map<int, int> m; 17 };哈希表的解法,我們把每個數字和其出現的次數建立映射,然后我們遍歷哈希表,對于每個值,我們先求出此值和目標值之間的差值t,然后我們需要分兩種情況來看,如果當前值不等于差值t,那么只要哈希表中有差值t就返回True,或者是當差值t等于當前值時,如果此時哈希表的映射次數大于1,則表示哈希表中還有另一個和當前值相等的數字,二者相加就是目標值
?
解法二:
1 class TwoSum { 2 public: 3 void add(int number) { 4 s.insert(number); 5 } 6 bool find(int value) { 7 for (auto a : s) { 8 int cnt = a == value - a ? 1 : 0; 9 if (s.count(value - a) > cnt) { 10 return true; 11 } 12 } 13 return false; 14 } 15 private: 16 unordered_multiset<int> s; 17 };另一種解法不用哈希表,而是unordered_multiset來做,但是原理和上面一樣
?
參考自:http://www.cnblogs.com/grandyang/p/5184143.html
?
轉載于:https://www.cnblogs.com/abc-begin/p/7715952.html
總結
以上是生活随笔為你收集整理的170. Two Sum III - Data structure design【easy】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到吃豆腐乳什么意思
- 下一篇: 梦到结婚好不好周公解梦