170 Two Sum III – Data structure design – Easy
Problem:
Thoughts:
Solutions:
public class TwoSum {
private HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
// Add the number to an internal data structure.
public void add(int number) {
// data.add(number);
if (count.containsKey(number)) {
count.put(number, count.get(number) + 1);
}
else {
count.put(number, 1);
}
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
for (Integer key:count.keySet()) {
if (2*key == value && count.get(key) >=2) {
return true;
}
if (2*key != value && count.containsKey(value - key)) {
return true;
}
}
return false;
}
}
// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum = new TwoSum();
// twoSum.add(number);
// twoSum.find(value);Last updated