-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path170.two-sum-iii-data-structure-design.java
More file actions
47 lines (41 loc) · 1.21 KB
/
Copy path170.two-sum-iii-data-structure-design.java
File metadata and controls
47 lines (41 loc) · 1.21 KB
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
38
39
40
41
42
43
44
45
46
import java.util.HashMap;
import java.util.Map;
/*
* @lc app=leetcode id=170 lang=java
*
* [170] Two Sum III - Data structure design
*/
// @lc code=start
class TwoSum {
Map<Integer, Integer> cntMap;
/** Initialize your data structure here. */
public TwoSum() {
cntMap = new HashMap<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
cntMap.put(number, cntMap.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 number: cntMap.keySet()) {
if (cntMap.get(number) <= 0) {
continue;
}
cntMap.put(number, cntMap.get(number) - 1);
if (cntMap.getOrDefault(value - number, 0) > 0) {
cntMap.put(number, cntMap.get(number) + 1);
return true;
}
cntMap.put(number, cntMap.get(number) + 1);
}
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);
*/
// @lc code=end