|
5 | 5 | import java.util.List;
|
6 | 6 | import java.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 | public class _170 {
|
28 |
| - public static class Solution1 { |
29 |
| - private Map<Integer, Integer> map = new HashMap(); |
30 |
| - private List<Integer> list = new ArrayList(); |
| 9 | + public static class Solution1 { |
| 10 | + class TwoSum { |
31 | 11 |
|
32 |
| - // Add the number to an internal data structure. |
33 |
| - public void add(int number) { |
34 |
| - list.add(number); |
35 |
| - map.put(number, map.getOrDefault(number, 0) + 1); |
36 |
| - } |
| 12 | + private Map<Integer, Integer> map; |
| 13 | + private List<Integer> list; |
| 14 | + |
| 15 | + /** |
| 16 | + * Initialize your data structure here. |
| 17 | + */ |
| 18 | + public TwoSum() { |
| 19 | + map = new HashMap(); |
| 20 | + list = new ArrayList(); |
| 21 | + } |
| 22 | + |
| 23 | + |
| 24 | + // Add the number to an internal data structure. |
| 25 | + public void add(int number) { |
| 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 |
| - public boolean find(int value) { |
40 |
| - for (int i = 0; i < list.size(); i++) { |
41 |
| - int val1 = list.get(i); |
42 |
| - int val2 = value - val1; |
43 |
| - if (map.containsKey(val2)) { |
44 |
| - if (val1 == val2) { |
45 |
| - if (map.get(val2) > 1) { |
46 |
| - return true; |
| 30 | + // Find if there exists any pair of numbers which sum is equal to the value. |
| 31 | + public boolean find(int value) { |
| 32 | + for (int i = 0; i < list.size(); i++) { |
| 33 | + int val1 = list.get(i); |
| 34 | + int val2 = value - val1; |
| 35 | + if (map.containsKey(val2)) { |
| 36 | + if (val1 == val2) { |
| 37 | + if (map.get(val2) > 1) { |
| 38 | + return true; |
| 39 | + } |
| 40 | + } else { |
| 41 | + return true; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + return false; |
47 | 46 | }
|
48 |
| - } else { |
49 |
| - return true; |
50 |
| - } |
51 | 47 | }
|
52 |
| - } |
53 |
| - return false; |
54 | 48 | }
|
55 |
| - } |
56 | 49 | }
|
0 commit comments