[LintCode] Problem 607 - Two Sum III - Data structure design

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) // return true
find(7) // return false

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 add(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;
}