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.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
呵呵呵奇葩了, 这个也是各种不过, 想找个完美解决方案,就去看讨论区别人的代码, 怎么都不满意, 突然发现一个我想要的代码, 心里一阵窃喜, 结果你猜这么着。那个代码发布者是我自己啊!!!尼玛!!摔键盘, 砸鼠标!
HashMap<Integer, Integer> map = new HashMap<>();
public void add(int number) {
map.put(number, map.getOrDefault(number,0) + 1);
}
public boolean find(int value) {
Set<Integer> keyset = map.keySet();
for(Integer key: keyset){
if(value == key * 2 && map.get(key) > 1
|| value != key * 2 && map.containsKey(value - key) ){
return true;
}
}
return false;
}