Two Sum III - Data structure design
add(1); add(3); add(5);
find(4) -> true
find(7) -> falseadd(3); add(1); add(2);
find(3) -> true
find(6) -> falseclass TwoSum {
HashMap<Integer,Integer> map = null;
/** Initialize your data structure here. */
public TwoSum() {
map = new HashMap<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
map.put(number,map.getOrDefault(number,0) + 1);
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
int diff = 0;
for(int num : map.keySet()){
diff = value - num;
if(map.containsKey(diff)){
if(diff !=num || map.get(diff) > 1 ){
return true;
}
}
}
return false;
}
}Last updated