File tree 1 file changed +17
-19
lines changed
src/main/java/com/fishercoder/solutions
1 file changed +17
-19
lines changed Original file line number Diff line number Diff line change 6
6
7
7
public class _296 {
8
8
public static class Solution1 {
9
+ /**
10
+ * Credit: https://leetcode.com/problems/best-meeting-point/solution/ Approach 3
11
+ */
9
12
public int minTotalDistance (int [][] grid ) {
10
13
int m = grid .length ;
11
14
int n = grid [0 ].length ;
12
-
13
- List <Integer > I = new ArrayList (m );
14
- List <Integer > J = new ArrayList (n );
15
-
15
+ List <Integer > rows = new ArrayList <>();
16
+ List <Integer > cols = new ArrayList <>();
16
17
for (int i = 0 ; i < m ; i ++) {
17
18
for (int j = 0 ; j < n ; j ++) {
18
19
if (grid [i ][j ] == 1 ) {
19
- I .add (i );
20
- J .add (j );
20
+ rows .add (i );
21
+ cols .add (j );
21
22
}
22
23
}
23
24
}
24
-
25
- return getMin (I ) + getMin (J );
25
+ int rowMedian = rows .get (rows .size () / 2 );
26
+ Collections .sort (cols );
27
+ int colMedian = cols .get (cols .size () / 2 );
28
+ return minDistance1D (rows , rowMedian ) + minDistance1D (cols , colMedian );
26
29
}
27
30
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 ++);
31
+ private int minDistance1D (List <Integer > points , int median ) {
32
+ int distance = 0 ;
33
+ for (int i : points ) {
34
+ distance += Math .abs (i - median );
37
35
}
38
-
39
- return ret ;
36
+ return distance ;
40
37
}
38
+
41
39
}
42
40
}
You can’t perform that action at this time.
0 commit comments