使用一个 list 存储 all unique numbers,另外用一个 HashMap 存储每个数字出现的个数。在query的时候,遍历 list,找每个 value-number 是否存在。另外要注意,如果一个数字加上其本身等于 value,就需要判断该数字的数量是否超过 1。
Java Code:
classTwoSum{privateMap<Integer,Integer> map =newHashMap<>();/** Initialize your data structure here. */publicTwoSum(){}/** Add the number to an internal data structure.. */publicvoidadd(intnumber){map.put(number,map.getOrDefault(number,0)+1);}/** Find if there exists any pair of numbers which sum is equal to the value. */publicbooleanfind(intvalue){for(Map.Entry<Integer,Integer> entry :map.entrySet()){int diff = value -entry.getKey();if(entry.getKey()== diff){if(entry.getValue()>1)returntrue;}elseif(map.containsKey(diff)){returntrue;}}returnfalse;}}
class TwoSum {
unordered_map<int, int> _map;
public:
/** Initialize your data structure here. */
TwoSum() {
}
/** Add the number to an internal data structure.. */
void add(int number) {
_map[number]++;
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
bool find(int value) {
for (auto pair : _map) {
int diff = value - pair.first;
if (diff == pair.first) {
if (pair.second > 1) return true;
} else if (_map.count(diff)) {
return true;
}
}
return false;
}
};