File tree 1 file changed +20
-5
lines changed
1 file changed +20
-5
lines changed Original file line number Diff line number Diff line change 1
1
package easy ;
2
2
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
+
5
8
6
9
//Your TwoSum object will be instantiated and called as such:
7
10
//TwoSum twoSum = new TwoSum();
8
11
//twoSum.add(number);
9
12
//twoSum.find(value);
10
13
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 ();
12
16
13
17
// Add the number to an internal data structure.
14
18
public void add (int number ) {
15
- set .add (number );
19
+ list .add (number );
20
+ map .put (number , map .getOrDefault (number , 0 )+1 );
16
21
}
17
22
18
23
// Find if there exists any pair of numbers which sum is equal to the value.
19
24
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 ;
21
36
}
22
37
}
You can’t perform that action at this time.
0 commit comments