Star

LeetCode 170. Two Sum III - Data Structure design

Question

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.

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

Explanation

和leetcode No.1一样,只是需要考虑的这里只能用一个不太需要维护的数据结构来存储,之前排序数组的那种方法就不可行了。同时要考虑计算frequency,会出现pair中两个数字是同一个的情况。

Code

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
public class TwoSum {
/** Initialize your data structure here. */
HashMap<Integer, Integer> map;
public TwoSum() {
map = new HashMap<Integer, Integer>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
if (map.containsKey(number)) {
map.put(number, map.get(number)+1);
} else {
map.put(number, 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 left = value - key;
if (left == key && map.get(key) > 1) {
return true;
} else if (left != key && map.containsKey(left)) {
return true;
}
}
return false;
}
}