Fork me on GitHub

two-sum-iii-data-structure-design

Description

https://leetcode.com/problems/two-sum-iii-data-structure-design/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class TwoSum {
public:
unordered_map<int, int> counter;
/** Initialize your data structure here. */
TwoSum() {

}

/** Add the number to an internal data structure.. */
void add(int number) {
counter[number] += 1;
}

/** Find if there exists any pair of numbers which sum is equal to the value. */
bool find(int value) {
for (auto& item : counter) {
int left = item.first;
int right = value - left;
if (left == right && item.second >= 2) return true;
if (left != right && counter.count(right) != 0) return true;

}

return false;
}
};

/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* bool param_2 = obj.find(value);
*/