Skip to content

Commit 8c59f17

Browse files
refactor 296
1 parent be573fe commit 8c59f17

File tree

1 file changed

+30
-24
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+30
-24
lines changed

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

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@
55
import java.util.List;
66

77
/**
8-
* A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
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|.
913
1014
For example, given three people living at (0,0), (0,4), and (2,2):
1115
@@ -17,36 +21,38 @@ For example, given three people living at (0,0), (0,4), and (2,2):
1721
The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.
1822
*/
1923
public class _296 {
20-
public int minTotalDistance(int[][] grid) {
21-
int m = grid.length;
22-
int n = grid[0].length;
23-
24-
List<Integer> I = new ArrayList(m);
25-
List<Integer> J = new ArrayList(n);
26-
27-
for (int i = 0; i < m; i++) {
28-
for (int j = 0; j < n; j++) {
29-
if (grid[i][j] == 1) {
30-
I.add(i);
31-
J.add(j);
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+
}
3238
}
3339
}
40+
41+
return getMin(I) + getMin(J);
3442
}
3543

36-
return getMin(I) + getMin(J);
37-
}
44+
private int getMin(List<Integer> list) {
45+
int ret = 0;
3846

39-
private int getMin(List<Integer> list) {
40-
int ret = 0;
47+
Collections.sort(list);
4148

42-
Collections.sort(list);
49+
int i = 0;
50+
int j = list.size() - 1;
51+
while (i < j) {
52+
ret += list.get(j--) - list.get(i++);
53+
}
4354

44-
int i = 0;
45-
int j = list.size() - 1;
46-
while (i < j) {
47-
ret += list.get(j--) - list.get(i++);
55+
return ret;
4856
}
49-
50-
return ret;
5157
}
5258
}

0 commit comments

Comments
 (0)