Skip to content

Commit 68f2d00

Browse files
refactor 296
1 parent 60fb83e commit 68f2d00

File tree

1 file changed

+34
-50
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+34
-50
lines changed

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

Lines changed: 34 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -4,55 +4,39 @@
44
import java.util.Collections;
55
import java.util.List;
66

7-
/**
8-
* 296: Best Meeting Point
9-
*
10-
* A group of two or more people wants to meet and minimize the total travel distance.
11-
* You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group.
12-
* The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
13-
14-
For example, given three people living at (0,0), (0,4), and (2,2):
15-
16-
1 - 0 - 0 - 0 - 1
17-
| | | | |
18-
0 - 0 - 0 - 0 - 0
19-
| | | | |
20-
0 - 0 - 1 - 0 - 0
21-
The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.
22-
*/
237
public class _296 {
24-
public static class Solution1 {
25-
public int minTotalDistance(int[][] grid) {
26-
int m = grid.length;
27-
int n = grid[0].length;
28-
29-
List<Integer> I = new ArrayList(m);
30-
List<Integer> J = new ArrayList(n);
31-
32-
for (int i = 0; i < m; i++) {
33-
for (int j = 0; j < n; j++) {
34-
if (grid[i][j] == 1) {
35-
I.add(i);
36-
J.add(j);
37-
}
38-
}
39-
}
40-
41-
return getMin(I) + getMin(J);
42-
}
43-
44-
private int getMin(List<Integer> list) {
45-
int ret = 0;
46-
47-
Collections.sort(list);
48-
49-
int i = 0;
50-
int j = list.size() - 1;
51-
while (i < j) {
52-
ret += list.get(j--) - list.get(i++);
53-
}
54-
55-
return ret;
56-
}
57-
}
8+
public static class Solution1 {
9+
public int minTotalDistance(int[][] grid) {
10+
int m = grid.length;
11+
int n = grid[0].length;
12+
13+
List<Integer> I = new ArrayList(m);
14+
List<Integer> J = new ArrayList(n);
15+
16+
for (int i = 0; i < m; i++) {
17+
for (int j = 0; j < n; j++) {
18+
if (grid[i][j] == 1) {
19+
I.add(i);
20+
J.add(j);
21+
}
22+
}
23+
}
24+
25+
return getMin(I) + getMin(J);
26+
}
27+
28+
private int getMin(List<Integer> list) {
29+
int ret = 0;
30+
31+
Collections.sort(list);
32+
33+
int i = 0;
34+
int j = list.size() - 1;
35+
while (i < j) {
36+
ret += list.get(j--) - list.get(i++);
37+
}
38+
39+
return ret;
40+
}
41+
}
5842
}

0 commit comments

Comments
 (0)