Design and implement a TwoSum class. It should support the following operations:addandfind.
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.
Have you met this question in a real interview?
Yes
Example
add(1); add(3); add(5);
find(4) // return true
find(7) // return false
class TwoSum {
unordered_multiset<int> nums;
public:
// Add the number to an internal data structure.
void add(int number) {
// Write your code here
nums.insert(number);
}
// Find if there exists any pair of numbers which sum is equal to the value.
bool find(int value) {
// Write your code here
for (int num : nums) {
int count = (num == value - num) ? 2 : 1;
if (nums.count(value - num) >= count) {
return true;
}
}
return false;
}
};
// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum;
// twoSum.add(number);
// twoSum.find(value);