Two Sum III - Data structure design
Design and implement a TwoSum class. It should support the following operations: add and find.
- Time: O(n)
- Space: O(1)
public class TwoSumIII {
Map<Integer, Integer> map = new HashMap<>();
public void add(int i) {
map.put(i, map.containsKey(i) ? map.get(i) + 1 : 1);
}
public boolean find(int target) {
for (Integer i : map.keySet()) {
if (map.containsKey(target - i)) {
if (i == target - i && map.get(i) < 2) {
continue;
}
return true;
}
}
return false;
}
}