File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments