
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.
Example
1 2 3
|
add(1); add(3); add(5); find(4) find(7)
|
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
private Map<Integer, Integer> map = new HashMap<>();
public void (int number) { map.put(number, map.getOrDefault(number, 0) + 1); }
public boolean find(int value) { for (Map.Entry<Integer, Integer> entry : map.entrySet()) { int val = value - entry.getKey();
if (map.containsKey(val)) { if (val * 2 != value) return true; else if (val * 2 == value && map.get(val) > 1) return true; } }
return false; }
|
近期评论