到所有人家距离之和最短的中点 296. Best Meeting Point

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了到所有人家距离之和最短的中点 296. Best Meeting Point脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Given an m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance.

The total travel distance is the sum of the distances between the houses of the friends and the meeting point.

The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

 

Example 1:

到所有人家距离之和最短的中点 296. Best Meeting Point

Input: grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 6
Explanation: Given three friends living at (0,0), (0,4), and (2,2).
The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal.
So return 6.

Example 2:

Input: grid = [[1,1]]
Output: 1中点距离最短,你说是就是吧。参考:https://leetcode.com/problems/best-meeting-point/discuss/74186/14ms-java-solution
class Solution {
    public int minTotalDistance(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        List<Integer> X = new ArrayList<>();
        List<Integer> Y = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    X.add(i);
                    Y.add(j);
                }
            }
        }
        return getMin(X) + getMin(Y);
    }
    
    private int getMin(List<Integer> nums) {
        Collections.sort(nums);
        int res = 0;
        int mid = nums.get(nums.size() / 2);
        for (int n : nums) {
            res += Math.abs(n - mid);
        }
        return res;
    }

 

 

脚本宝典总结

以上是脚本宝典为你收集整理的到所有人家距离之和最短的中点 296. Best Meeting Point全部内容,希望文章能够帮你解决到所有人家距离之和最短的中点 296. Best Meeting Point所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: