[leetcode] 296. Best Meeting Point 解题报告
来源:互联网 发布:最强网络神豪 编辑:程序博客网 时间:2024/06/07 19:53
题目链接: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; }};
- [leetcode] 296. Best Meeting Point 解题报告
- [Leetcode] 296. Best Meeting Point 解题报告
- [LeetCode] Best Meeting Point
- leetcode: Best Meeting Point
- 296. Best Meeting Point
- 296. Best Meeting Point
- leetcode 296: Best Meeting Point
- Leetcode 296Best Meeting Point
- LeetCode 296: Best Meeting Point
- LeetCode 296. Best Meeting Point(最佳见面点)
- LeetCode 题解(279) :Best Meeting Point
- best meeting point
- [LeetCode296]Best Meeting Point
- Best Meeting Point
- [leetcode] 252. Meeting Rooms 解题报告
- [leetcode] 253. Meeting Rooms II 解题报告
- [Leetcode] 252. Meeting Rooms 解题报告
- [Leetcode] 253. Meeting Rooms II 解题报告
- css3中webkit-box的用法
- Linux与JVM的内存关系分析
- 解决Glide加载圆形图片,第一次只显示点位图的问题
- adump,bdump,cdump,dpdump文件各表示什么含义?
- 兼容性问题整理小记
- [leetcode] 296. Best Meeting Point 解题报告
- dual
- 跟我一起学Microsoft SQL Server 2012 Internals(1.4)
- ORA-39168: Object path STATISTICS was not found.
- 宏定义和函数
- Sizeof与Strlen的区别与联系(转)
- 数据结构入门
- iOS 图片编辑——涂鸦——带剪头的线条
- 大二寒假