Two Sum III - Data structure design
Written on November 5, 2015
Tweet
Design and implement a TwoSum class. It should support the following operations: add and find.</p> add - Add the number to an internal data structure.</p> find - Find if there exists any pair of numbers which sum is equal to the value.
public class TwoSum {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
// Add the number to an internal data structure.
public void add(int number) {
if (!map.containsKey(number)) {
map.put(number, 1);
} else {
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 (int key : map.keySet()) {
int other = value - key;
if ((other == key && map.get(key) >= 2) || (other != key && map.containsKey(other))) {
return true;
}
}
return false;
}
}