Skip to content

Commit f24dcb8

Browse files
refactor 170
1 parent 19b279c commit f24dcb8

File tree

1 file changed

+35
-42
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+35
-42
lines changed

src/main/java/com/fishercoder/solutions/_170.java

Lines changed: 35 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -5,52 +5,45 @@
55
import java.util.List;
66
import java.util.Map;
77

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-
278
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 {
3111

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+
}
3729

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;
4746
}
48-
} else {
49-
return true;
50-
}
5147
}
52-
}
53-
return false;
5448
}
55-
}
5649
}

0 commit comments

Comments
 (0)