classTwoSum { public: unordered_map<int, int> counter; /** Initialize your data structure here. */ TwoSum() { } /** Add the number to an internal data structure.. */ voidadd(int number){ counter[number] += 1; } /** Find if there exists any pair of numbers which sum is equal to the value. */ boolfind(int value){ for (auto& item : counter) { int left = item.first; int right = value - left; if (left == right && item.second >= 2) returntrue; if (left != right && counter.count(right) != 0) returntrue; } returnfalse; } };
/** * Your TwoSum object will be instantiated and called as such: * TwoSum obj = new TwoSum(); * obj.add(number); * bool param_2 = obj.find(value); */