forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_296.java
42 lines (33 loc) · 1011 Bytes
/
_296.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class _296 {
public static class Solution1 {
public int minTotalDistance(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
List<Integer> I = new ArrayList(m);
List<Integer> J = new ArrayList(n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
I.add(i);
J.add(j);
}
}
}
return getMin(I) + getMin(J);
}
private int getMin(List<Integer> list) {
int ret = 0;
Collections.sort(list);
int i = 0;
int j = list.size() - 1;
while (i < j) {
ret += list.get(j--) - list.get(i++);
}
return ret;
}
}
}