题目链接:https://leetcode.com/problems/best-meeting-point/
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 usingManhattan 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.
思路: 先在一维上解决这个问题.
相当于在一条直线上有A,B,C,D,E五个点, 我们要在这个直线上找到一个点P, 使得所有点到P点的距离之和最小.
我们可以看到到A,E两点距离之和的点肯定在A, E之间, 而到B,D两点最短距离的点是在B,D之间, 而到C最短的点就只有在C上了, 这是奇数个点的情况, 偶数各点可以在最中间两个点之间的任意位置. 因此我们要找的点其实就是所有点的中位数, 而不是平均数. 所以只需要将这几个点的x, y左边分别记录下来, 然后进行排序, 因为其距离是按照曼哈顿距离来算, 因此x和y轴是互不干扰的, 其各自中位数就是我们要找的最佳见面位置.
代码如下:
class Solution { public: int minTotalDistance(vector<vector<int>>& grid) { if(grid.size() == 0) return 0; int sum=0, m = grid.size(), n = grid[0].size(); vector<int> hash_x, hash_y; for(int i = 0; i< m; i++) for(int j = 0; j< n; j++) if(grid[i][j] == 1) { hash_x.push_back(i); hash_y.push_back(j); } sort(hash_x.begin(), hash_x.end()); sort(hash_y.begin(), hash_y.end()); int len = hash_x.size(); for(int i = 0; i< len; i++) sum += abs(hash_x[i]-hash_x[len/2]) + abs(hash_y[i]-hash_y[len/2]); return sum; } };