170. 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.

For example,

1
2
3
add(1); add(3); add(5);
find(4) -> true
find(7) -> false

解法1:

要注意一些细节。需要排除找到的数字不是自己,所以要统计每一个数字出现的次数。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class TwoSum {
/** Initialize your data structure here. */
HashMap<Integer, Integer> map = null;
public TwoSum() {
map = new HashMap<Integer, Integer>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
map.put(number, map.getOrDefault(number, 0) + 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 target = value - key;
if (target == key && map.get(key) > 1 ) {
return true;
} else if (target != key && map.containsKey(target)) {
return true;
}
}
return false;
}
}
/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* boolean param_2 = obj.find(value);
*/