链接:https://leetcode.com/tag/design/

【146】LRU Cache 

 

【155】Min Stack 

 

【170】Two Sum III - Data structure design (2018年12月6日,周四)

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.

Example 1:
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
Example 2:
add(3); add(1); add(2);
find(3) -> true
find(6) -> false

题解:无

 1 class TwoSum {
 2 public:
 3     /** Initialize your data structure here. */
 4     TwoSum() {
 5         
 6     }
 7     
 8     /** Add the number to an internal data structure.. */
 9     void add(int number) {
10         nums.push_back(number);
11         mp[number]++;
12     }
13     
14     /** Find if there exists any pair of numbers which sum is equal to the value. */
15     bool find(int value) {
16         for (auto ele : nums) {
17             int target = value - ele;
18             if (mp.find(target) != mp.end()) {
19                 if (target == ele && mp[target] >= 2 || target != ele && mp[target] >= 1) {
20                     return true;
21                 }
22             }
23         }
24         return false;
25     }
26     vector<int> nums;
27     unordered_map<int, int> mp;
28 };
29 
30 /**
31  * Your TwoSum object will be instantiated and called as such:
32  * TwoSum obj = new TwoSum();
33  * obj.add(number);
34  * bool param_2 = obj.find(value);
35  */
View Code

相关文章: