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:
思路:
用hashmap,因为会有重复数字,需要计数。分为两种情况判断,是否和当前值不一样,如果一样,查询差值是否存在;如果一样,必须要求差值的数量>1。
易错点
- 用修改hash值的方法会出错
class TwoSum {
public:
/** Initialize your data structure here. */
TwoSum() {
}
/** Add the number to an internal data structure.. */
void add(int number) {
++hash[number];
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
bool find(int value) {
for (auto & item: hash){
int t = value - item.first;
if (t != item.first && hash.count(t)) {
return true;
}
else if (t == item.first && hash[t] > 1){
return true;
}
}
return false;
}
private:
unordered_map<int, int> hash;
};
/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* bool param_2 = obj.find(value);
*/