forked from jsjtzyy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC170_TwoSumIII_Design.java
More file actions
37 lines (34 loc) · 973 Bytes
/
LC170_TwoSumIII_Design.java
File metadata and controls
37 lines (34 loc) · 973 Bytes
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
34
35
36
37
import java.util.*;
public class LC170_TwoSumIII_Design {
Map<Integer, Integer> map;
public LC170_TwoSumIII_Design(){
map = new HashMap<>();
}
// Add the number to an internal data structure.
public void add(int number) {
if(map.containsKey(number)){
map.put(number, 2);
}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) {
if(value % 2 == 0 && map.containsKey(value / 2)){
if(map.get(value / 2) == 2) return true;
map.remove(value / 2);
for(Integer num : map.keySet()){
if(map.containsKey(value - num)) {
map.put(value / 2, 1);
return true;
}
}
map.put(value / 2, 1);
}else{
for(Integer num : map.keySet()){
if(map.containsKey(value - num)) return true;
}
}
return false;
}
}