码迷,mamicode.com
首页 > 其他好文 > 详细

Best Meeting Point

时间:2016-08-05 06:23:16      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

Total Accepted: 701 Total Submissions: 1714 Difficulty: Medium

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.

分析:http://massivealgorithms.blogspot.com/2015/10/leetcode-best-meeting-point-segmentfault.html

首先,Manhattan Distance 的合为 sum(distance(p1, p2)) = sum(|p2.x - p1.x| + |p2.y - p1.y|)= sum(|p2.x - p1.x|)+sum(|p2.y - p1.y|). 也就是说, 可以分别计算x和y的合, 然后加起来.
其次, 我们需要把2d的grid变成1d, 这里的窍门是, 我们可以证明, 所求的点, 就在其中某点的x或者y的坐标轴上. 所以, 而这点, 必然是1d下的median. http://math.stackexchange.com/questions/113270/the-median-minimizes-the-sum-of-absolute-deviations

Suppose we have a set S of real numbers that ∑s∈S|s−x|is minimal if x is equal to themedian.

所以, 我们需要count一下x轴上有多少个1的投影, 和y轴上有多少个1的投影. 就可以找到这个median. 这里我们不需要sorting, 因为投影本身就是已排序的.
最后, 我们得到一个1d的array, 我们需要计算以上公式,即各点到median的值的合, 这里需要用two pointers, 因为array本身已经是排序过后的了, 所以我们只需要求两头的元素的差值的合, 就是他们到median的合.
技术分享

6是median,那么 (6-2)+(6-4) + (6-5) + (7-6) + (8-6) + (9-6) = 4 + 2+ 1+ 1+ 2+ 3 = 13 = (9-2) + (8-4) + (7-5)

public class Solution {
    public int minTotalDistance(int[][] grid) {
        List<Integer> xPoints = new ArrayList<>();
        List<Integer> yPoints = new ArrayList<>();

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    xPoints.add(i);
                    yPoints.add(j);
                }
            }
        }

        return getMP(xPoints) + getMP(yPoints);
    }

    private int getMP(List<Integer> points) {
        Collections.sort(points);
        int i = 0, j = points.size() - 1;
        int res = 0;
        while (i < j) {
            res += points.get(j--) - points.get(i++);
        }
        return res;
    }
}

 

Best Meeting Point

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5739020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!