-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path170.two-sum-iii-data-structure-design.java
More file actions
42 lines (38 loc) · 1.04 KB
/
170.two-sum-iii-data-structure-design.java
File metadata and controls
42 lines (38 loc) · 1.04 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
/*
* @lc app=leetcode id=170 lang=java
*
* [170] Two Sum III - Data structure design
*/
// @lc code=start
class TwoSum {
private Map<Integer, Integer> map;
/** Initialize your data structure here. */
public TwoSum() {
map = new HashMap<>();
}
/** 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 num = value - key;
if (num != key) {
if (map.containsKey(num)) {
return true;
}
} else if (map.get(key) > 1) {
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);
*/
// @lc code=end