296. 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 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:
- Try to solve it in one dimension first. How can this solution apply to the two dimension case?
链接: http://leetcode.com/problems/best-meeting-point/
题解:
很有意思的一道题目,假设二维数组中一个点到其他给定点的Manhattan Distance最小,求distance和。 因为在一维数组中这个distance最小的点就是给定所有点的median,题目又给定使用曼哈顿距离,我们就可以把二维计算分解成为两个一维的计算。应该还可以用DP的方法解决,判断用哪一种方法其实非常复杂,依赖于mn和排序的比较。我们使用一个getMin方法来计算x方向或者y方向到他们中点的距离和。
Time Complexity - Math.max(O(mn), O(nlogn)), Space Complexity - O(mn)。
public class Solution {
public int minTotalDistance(int[][] grid) {
List<Integer> xAxis = new ArrayList<>();
List<Integer> yAxis = new ArrayList<>(); for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == 1) {
xAxis.add(i);
yAxis.add(j);
}
}
} return getMin(xAxis) + getMin(yAxis);
} private int getMin(List<Integer> list) {
Collections.sort(list);
int res = 0;
int lo = 0, hi = list.size() - 1;
while(lo < hi) {
res += list.get(hi--) - list.get(lo++); // hi - mid + mid - lo = hi - lo
}
return res;
}
}
二刷:
还是用了简单地先遍历一遍数组,收集行坐标和列坐标,然后对两个list分别求一维Manhattan距离的方法。这里对列坐标list进行了排序。
Java:
Time Complexity - Math.max(O(mn), O(nlogn)), Space Complexity - O(mn)。
public class Solution {
public int minTotalDistance(int[][] grid) {
List<Integer> rows = new ArrayList<>(), cols = new ArrayList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
rows.add(i);
cols.add(j);
}
}
}
Collections.sort(cols);
return getMinDist(rows) + getMinDist(cols);
} private int getMinDist(List<Integer> list) {
if (list == null || list.size() == 0) return Integer.MAX_VALUE;
int median = list.get(list.size() / 2);
int minDist = 0;
for (int idx : list) {
if (idx < median) minDist += median - idx;
else minDist += idx - median;
}
return minDist;
}
}
Update:
遍历两次数组,分别对行列坐标进行收集,速度反而比较快。应该是不少test case中m < logn的缘故。
Time Complexity - O(mn), O(nlogn), Space Complexity - O(mn)。
public class Solution {
public int minTotalDistance(int[][] grid) {
List<Integer> rows = new ArrayList<>(), cols = new ArrayList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) rows.add(i);
}
}
for (int j = 0; j < grid[0].length; j++) {
for (int i = 0; i < grid.length; i++) {
if (grid[i][j] == 1) cols.add(j);
}
}
return getMinDist(rows) + getMinDist(cols);
} private int getMinDist(List<Integer> list) {
if (list == null || list.size() == 0) return Integer.MAX_VALUE;
int median = list.get(list.size() / 2);
int minDist = 0;
for (int idx : list) {
if (idx < median) minDist += median - idx;
else minDist += idx - median;
}
return minDist;
}
}
Update:
不计算median,利用median - lo + hi - median = hi - lo,同时计算lo和hi到median的距离。来自大神larrywang2014的写法。
public class Solution {
public int minTotalDistance(int[][] grid) {
List<Integer> rows = new ArrayList<>(), cols = new ArrayList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) rows.add(i);
}
}
for (int j = 0; j < grid[0].length; j++) {
for (int i = 0; i < grid.length; i++) {
if (grid[i][j] == 1) cols.add(j);
}
}
return getMinDist(rows) + getMinDist(cols);
} private int getMinDist(List<Integer> list) {
if (list == null || list.size() == 0) return Integer.MAX_VALUE;
int minDist = 0;
int lo = 0, hi = list.size() - 1;
while (lo < hi) {
minDist += list.get(hi--) - list.get(lo++); // median - lo + hi - median = hi - lo
}
return minDist;
}
}
Reference:
https://leetcode.com/discuss/65336/14ms-java-solution
https://leetcode.com/discuss/65366/o-mn-java-2ms
https://leetcode.com/discuss/65464/java-python-40ms-pointers-solution-median-sort-explanation
https://leetcode.com/discuss/66401/the-only-person-dont-know-median-could-give-shortest-distance
http://math.stackexchange.com/questions/113270/the-median-minimizes-the-sum-of-absolute-deviations
https://leetcode.com/discuss/65510/simple-java-code-without-sorting
http://www.jiuzhang.com/problem/30/
296. Best Meeting Point的更多相关文章
- [LeetCode] 296. Best Meeting Point 最佳开会地点
A group of two or more people wants to meet and minimize the total travel distance. You are given a ...
- 【leetcode】296.Best Meeting Point
原题 A group of two or more people wants to meet and minimize the total travel distance. You are given ...
- LeetCode All in One 题目讲解汇总(持续更新中...)
终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...
- LeetCode题目按公司分类
LinkedIn(39) 1 Two Sum 23.0% Easy 21 Merge Two Sorted Lists 35.4% Easy 23 Merge k Sorted Lists 23.3% ...
- LeetCode All in One题解汇总(持续更新中...)
突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...
- Leetcode重点 250题-前400 题
删除不常考,面试低频出现题目 删除重复代码题目(例:链表反转206题,代码在234题出现过) 删除过于简单题目(例:100题:Same Tree) 删除题意不同,代码基本相同题目(例:136 & ...
- LeetCode分类-前400题
1. Array 基础 27 Remove Element 26 Remove Duplicates from Sorted Array 80 Remove Duplicates from Sorte ...
- Hard模式题目
先过一下Hard模式的题目吧. # Title Editorial Acceptance Difficulty Frequency . 65 Valid Number 12.6% Ha ...
- 继续过Hard题目
接上一篇:http://www.cnblogs.com/charlesblc/p/6283064.html 继续过Hard模式的题目吧. # Title Editorial Acceptance ...
随机推荐
- mongodb修改器
mongodb修改器 转载自:http://blog.csdn.net/mcpang/article/details/7752736 mongodb修改器(\(inc/\)set/\(unset/\) ...
- (转载)HTML:模拟链接被按下,在新标签页打开页面,不使用window.open(可能被拦截)
原文: http://www.cppblog.com/biao/archive/2010/08/21/124196.html 当按下一个按钮时,想打开一个新的标签页,可以使用window.open去实 ...
- Eclipse的python插件安装
网上找了一些资料都没有成功~~然后自己装的过程中编辑记录了一些 当然博客园里也有人用这一种方法也可以参考IBM中的 http://www.cnblogs.com/visec479/p/4139882. ...
- Grails 对象关联映射 (GORM) 一
转自:http://justjavac.iteye.com/blog/701445 Domain 类是任何商业应用的核心. 他们保存事务处理的状态,也处理预期的行为. 他们通过关联联系在一起, one ...
- bzoj 1189 二分+最大流判定
首先我们可以二分一个答案时间T,这样就将最优性问题 转化为了判定性问题.下面我们考虑对于已知的T的判定 对于矩阵中所有的空点bfs一次,得出来每个点到门的距离, 然后连接空点和每个能在t时间内到达的门 ...
- 【BZOJ】【1027】【JSOI2007】合金
计算几何/凸包/Floyd Orz rausen大爷太强辣 计算几何题目果然不会做>_> 这个题……虽然他给了3个坐标,但实际上是个二维的计算几何题= =因为第三维坐标可以直接用前两维坐标 ...
- 设计模式 - Template Method
今天下午主要研究了设计模式中的Template Method(模版方法设计模式). 在Spring中,对各种O/RM进行了封装,比如对Hibernate有HibernateTemplate封装:对JD ...
- NYOJ-21 三个水杯 AC 分类: NYOJ 2014-02-08 11:35 174人阅读 评论(0) 收藏
人生中第一个AC的广搜题目,喵呜,C++的STL果真不错, #include<stdio.h> #include<queue> #include<string.h> ...
- CoreText 使用教程
[iOS开发] CoreText 使用教程:以创建一个简单的杂志应用为例抢沙发 分类:iPhone开发 标签:CoreText.iOS.iOS开发.iOS开发教程.杂志应用 BBS.CHINAAPP. ...
- yebis error ---depth of field
前几天在墙外无法登陆cnblogs...导致很多blogs就没写了 有几篇比较值得记下来的,但是我已经不记得了,应该和sao有关scalable ambient obscurance 我似乎回忆起一点 ...