|
5 | 5 | importjava.util.List;
|
6 | 6 | importjava.util.Map;
|
7 | 7 |
|
8 |
| -/** |
9 |
| - * 170. Two Sum III - Data structure design |
10 |
| - * |
11 |
| - * Design and implement a TwoSum class. It should support the following operations: add and find. |
12 |
| - * |
13 |
| - * add - Add the number to an internal data structure. |
14 |
| - * find - Find if there exists any pair of numbers which sum is equal to the value. |
15 |
| - * |
16 |
| - * Example 1: |
17 |
| - * add(1); add(3); add(5); |
18 |
| - * find(4) -> true |
19 |
| - * find(7) -> false |
20 |
| - * |
21 |
| - * Example 2: |
22 |
| - * add(3); add(1); add(2); |
23 |
| - * find(3) -> true |
24 |
| - * find(6) -> false |
25 |
| - */ |
26 |
| - |
27 | 8 | publicclass_170 {
|
28 |
| -publicstaticclassSolution1 { |
29 |
| -privateMap<Integer,Integer>map =newHashMap(); |
30 |
| -privateList<Integer>list =newArrayList(); |
| 9 | +publicstaticclassSolution1 { |
| 10 | +classTwoSum { |
31 | 11 |
|
32 |
| -// Add the number to an internal data structure. |
33 |
| -publicvoidadd(intnumber) { |
34 |
| -list.add(number); |
35 |
| -map.put(number,map.getOrDefault(number,0) +1); |
36 |
| - } |
| 12 | +privateMap<Integer,Integer>map; |
| 13 | +privateList<Integer>list; |
| 14 | + |
| 15 | +/** |
| 16 | + * Initialize your data structure here. |
| 17 | + */ |
| 18 | +publicTwoSum() { |
| 19 | +map =newHashMap(); |
| 20 | +list =newArrayList(); |
| 21 | + } |
| 22 | + |
| 23 | + |
| 24 | +// Add the number to an internal data structure. |
| 25 | +publicvoidadd(intnumber) { |
| 26 | +list.add(number); |
| 27 | +map.put(number,map.getOrDefault(number,0) +1); |
| 28 | + } |
37 | 29 |
|
38 |
| -// Find if there exists any pair of numbers which sum is equal to the value. |
39 |
| -publicbooleanfind(intvalue) { |
40 |
| -for (inti =0;i <list.size();i++) { |
41 |
| -intval1 =list.get(i); |
42 |
| -intval2 =value -val1; |
43 |
| -if (map.containsKey(val2)) { |
44 |
| -if (val1 ==val2) { |
45 |
| -if (map.get(val2) >1) { |
46 |
| -returntrue; |
| 30 | +// Find if there exists any pair of numbers which sum is equal to the value. |
| 31 | +publicbooleanfind(intvalue) { |
| 32 | +for (inti =0;i <list.size();i++) { |
| 33 | +intval1 =list.get(i); |
| 34 | +intval2 =value -val1; |
| 35 | +if (map.containsKey(val2)) { |
| 36 | +if (val1 ==val2) { |
| 37 | +if (map.get(val2) >1) { |
| 38 | +returntrue; |
| 39 | + } |
| 40 | + }else { |
| 41 | +returntrue; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | +returnfalse; |
47 | 46 | }
|
48 |
| - }else { |
49 |
| -returntrue; |
50 |
| - } |
51 | 47 | }
|
52 |
| - } |
53 |
| -returnfalse; |
54 | 48 | }
|
55 |
| - } |
56 | 49 | }
|