Skip to content

Commit 9559be4

Browse files
authored
Create 170. Two Sum III - Data structure design.java
1 parent 35f6535 commit 9559be4

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public class TwoSum {
2+
ArrayList<Integer> list;
3+
HashMap<Integer, Integer> map;
4+
5+
/** Initialize your data structure here. */
6+
public TwoSum() {
7+
list = new ArrayList<>();
8+
map = new HashMap<>();
9+
}
10+
11+
/** Add the number to an internal data structure.. */
12+
public void add(int number) {
13+
if (!map.containsKey(number)) {
14+
map.put(number, 1);
15+
} else {
16+
map.put(number, map.get(number) + 1);
17+
}
18+
list.add(number);
19+
}
20+
21+
/** Find if there exists any pair of numbers which sum is equal to the value. */
22+
public boolean find(int value) {
23+
for (Integer i : list) {
24+
if (((i == value - i) && map.get(i) > 1)
25+
|| ((i != value - i) && map.containsKey(value-i))) {
26+
return true;
27+
}
28+
}
29+
return false;
30+
}
31+
}
32+
33+
/**
34+
* Your TwoSum object will be instantiated and called as such:
35+
* TwoSum obj = new TwoSum();
36+
* obj.add(number);
37+
* boolean param_2 = obj.find(value);
38+
*/

0 commit comments

Comments
 (0)