Best Meeting Point 解答

Question

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|.

For example, given three people living at (0,0)(0,4), and (2,2):

1 - 0 - 0 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0

The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.

Hint:

  1. Try to solve it in one dimension first. How can this solution apply to the two dimension case?

Solution 1 -- Sort

根据曼哈顿距离的表达式,我们可以把这个问题转化为求每一维的最短距离。

总距离 = x上最短总距离 + y上最短总距离

并且,我们观察到,对于一个序列,如 [0,0,1,0,1,0,1,1,1,0,0,1]

当邮局选在median的位置时,距离和是最小的。

因此,这里我们遍历数组,得到home的x和y坐标值,然后分别对这两个list排序。再用双指针得到总的最短距离和。

Time complexity O(mn log(mn))

 public class Solution {
public int minTotalDistance(int[][] grid) {
if (grid == null || grid.length < 1) {
return 0;
}
int m = grid.length, n = grid[0].length;
List<Integer> xList = new ArrayList<Integer>();
List<Integer> yList = new ArrayList<Integer>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
xList.add(i);
yList.add(j);
}
}
}
return calcTotalDistance(xList) + calcTotalDistance(yList);
} private int calcTotalDistance(List<Integer> list) {
if (list == null || list.size() < 2) {
return 0;
}
Collections.sort(list);
int len = list.size();
int i = 0, j = len - 1;
int result = 0;
while (i < j) {
int left = list.get(i);
int right = list.get(j);
result += (right - left);
i++;
j--;
}
return result;
}
}

Solution 2 -- Without sorting

Discussion里有人给出了不用排序的方法。时间复杂度降低为O(mn)

因为双层循环遍历数组本身就是有次序性的。

1. 外层循环为遍历行,内层循环为遍历该行的每一个元素。

这样得到的是排序好的x的list

2. 外层循环为遍历列,内层循环为遍历该列的每一个元素。

这样得到的是排序好的y的list

 public class Solution {
public int minTotalDistance(int[][] grid) {
if (grid == null || grid.length < 1) {
return 0;
}
int m = grid.length, n = grid[0].length;
List<Integer> xList = new ArrayList<Integer>();
List<Integer> yList = new ArrayList<Integer>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
xList.add(i);
}
}
}
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
if (grid[i][j] == 1) {
yList.add(j);
}
}
} return calcTotalDistance(xList) + calcTotalDistance(yList);
} private int calcTotalDistance(List<Integer> list) {
if (list == null || list.size() < 2) {
return 0;
}
int len = list.size();
int i = 0, j = len - 1;
int result = 0;
while (i < j) {
result += (list.get(j--) - list.get(i++));
}
return result;
}
}
上一篇:logback不输出日志消息,且SLF4J绑定源错误


下一篇:centos 下搭建 php环境(1)