题目:

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?

链接: 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的更多相关文章

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

  2. 【leetcode】296.Best Meeting Point

    原题 A group of two or more people wants to meet and minimize the total travel distance. You are given ...

  3. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  4. LeetCode题目按公司分类

    LinkedIn(39) 1 Two Sum 23.0% Easy 21 Merge Two Sorted Lists 35.4% Easy 23 Merge k Sorted Lists 23.3% ...

  5. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  6. Leetcode重点 250题-前400 题

    删除不常考,面试低频出现题目 删除重复代码题目(例:链表反转206题,代码在234题出现过) 删除过于简单题目(例:100题:Same Tree) 删除题意不同,代码基本相同题目(例:136 & ...

  7. LeetCode分类-前400题

    1. Array 基础 27 Remove Element 26 Remove Duplicates from Sorted Array 80 Remove Duplicates from Sorte ...

  8. Hard模式题目

    先过一下Hard模式的题目吧.   # Title Editorial Acceptance Difficulty Frequency   . 65 Valid Number     12.6% Ha ...

  9. 继续过Hard题目

    接上一篇:http://www.cnblogs.com/charlesblc/p/6283064.html 继续过Hard模式的题目吧.   # Title Editorial Acceptance ...

随机推荐

  1. [Z] 深入浅出 Systemd

    1. Systemd 的简介和特点 Systemd 是 Linux 系统中最新的初始化系统(init),它主要的设计目标是克服 sysvinit 固有的缺点,提高系统的启动速度.systemd 和 u ...

  2. GitHub教程--上传项目四步法 GitBash命令行下使用方法

    之前就用过GitHub,感觉用GitHub托管自己的代码非常不错.可是之前用的都是窗口化的TortoiseGit,省了很多命令行的操作,但是个人非常喜欢使用命令行,于是,今天就试着用了用GitBash ...

  3. Class类工具 - ClassUtils.java

    Class类工具,提供操作class类的方法.<br/>比如:获知类.方法上是否有注解,获取类注解,获取某package下所有class等. 源码如下:(点击下载 - ClassUtils ...

  4. Upgrading to Java 8——第一章 Lambda表达式

    第一章 Lambda表达式 Lamada 表达式是Java SE 8中最重要的新特性,长期以来被认为是在Java中缺失的特性,它的出现使整个java 语言变得完整.至少到目前,在这节中你将学习到什么是 ...

  5. Mybatis错误调试(二)

    错误日志信息:  Caused by: java.sql.BatchUpdateException: ORA-00911: 无效字符 at oracle.jdbc.driver.OraclePrepa ...

  6. 【Python】网络编程

    1.TCP编程 2.SocketServer模块 3.Twisted框架 4.UDP编程 1.TCP编程--TCP是面向连接的,其一般的设计如下: # encoding:utf-8 ''' Creat ...

  7. hdu 3061 Battle 最大权闭合图

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3061 由于小白同学近期习武十分刻苦,很快被晋升为天策军的统帅.而他上任的第一天,就面对了一场极其困难的 ...

  8. Leetcode#140 Word Break II

    原题地址 动态规划题 令s[i..j]表示下标从i到j的子串,它的所有分割情况用words[i]表示 假设s[0..i]的所有分割情况words[i]已知.则s[0..i+1]的分割情况words[i ...

  9. Web流程

    Web阻塞加载,异步加载. 延迟执行,立即执行. 加载并执行,不要调用代码. 加载并执行时会调用代码,但是加载并执行时不要调用代码,否则会改变逻辑. 上面是Web流程,JS只是web的一部分.如果关注 ...

  10. angularjs取Sevice和directive的引用

    取Sevice和directive的引用 3: Grab any Services We can grab a reference to any service using the injector  ...