My code:
public class Solution {
public int minTotalDistance(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return -1;
}
int row = grid.length;
int col = grid[0].length;
int[] row_compress = new int[col];
int[] col_compress = new int[row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
row_compress[j] += grid[i][j];
col_compress[i] += grid[i][j];
}
}
return helper(row_compress) + helper(col_compress);
}
private int helper(int[] arr) {
int i = -1;
int j = arr.length;
int left = 0;
int right = 0;
int d = 0;
while (i != j) {
if (left < right) {
d += left;
left += arr[++i];
}
else {
d += right;
right += arr[--j];
}
}
return d;
}
}
https://leetcode.com/articles/best-meeting-point/#approach-3-sorting-accepted
这道题目真是卡了很久,到现在其实也没完全懂。暂且记下这个做法吧。
Anyway, Good luck, Richardo! -- 10/08/2016
网友评论