题目
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.
答案
class TwoSum {
Map<Integer, Integer> map;
/** Initialize your data structure here. */
public TwoSum() {
map = new HashMap<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
map.putIfAbsent(number, 0);
map.put(number, map.get(number) + 1);
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
for(Map.Entry<Integer, Integer> e : map.entrySet()) {
int key = e.getKey();
int val = e.getValue();
Integer diff_cnt = map.get(value - key);
if(diff_cnt == null) continue;
if(value - key == key) {
if(diff_cnt > 1) return true;
}
else {
return true;
}
}
return false;
}
}
/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* boolean param_2 = obj.find(value);
*/