题目链接: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) {
vector<int> X, Y;
for(int i =0; i < grid.size(); i++)
{
for(int j =0; j < grid[0].size(); j++)
{
if(grid[i][j] != 1) continue;
X.push_back(i);
Y.push_back(j);
}
}
nth_element(X.begin(), X.begin()+X.size()/2, X.end());
nth_element(Y.begin(), Y.begin()+Y.size()/2, Y.end());
int ans=0, xMed = X[X.size()/2], yMed = Y[Y.size()/2];
for(int i =0; i < X.size(); i++)
ans += abs(X[i]-xMed) + abs(Y[i]-yMed);
return ans;
}
};