Skip to content

Commit deaefd8

Browse files
EASY/src/easy/TwoSumIIIDataStructureDesign.java
1 parent 95a44e4 commit deaefd8

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,37 @@
11
package easy;
22

3-
import java.util.HashSet;
4-
import java.util.Set;
3+
import java.util.ArrayList;
4+
import java.util.HashMap;
5+
import java.util.List;
6+
import java.util.Map;
7+
58

69
//Your TwoSum object will be instantiated and called as such:
710
//TwoSum twoSum = new TwoSum();
811
//twoSum.add(number);
912
//twoSum.find(value);
1013
public class TwoSumIIIDataStructureDesign {
11-
private Set<Integer> set = new HashSet();
14+
private Map<Integer, Integer> map = new HashMap();
15+
private List<Integer> list = new ArrayList();
1216

1317
// Add the number to an internal data structure.
1418
public void add(int number) {
15-
set.add(number);
19+
list.add(number);
20+
map.put(number, map.getOrDefault(number, 0)+1);
1621
}
1722

1823
// Find if there exists any pair of numbers which sum is equal to the value.
1924
public boolean find(int value) {
20-
return
25+
for(int i = 0; i < list.size(); i++){
26+
int val1 = list.get(i);
27+
int val2 = value-val1;
28+
if(map.containsKey(val2)) {
29+
if(val1 == val2) {
30+
if(map.get(val2) > 1) return true;
31+
}
32+
else return true;
33+
}
34+
}
35+
return false;
2136
}
2237
}

0 commit comments

Comments
 (0)