九章算法 | 阿里面试题:取物资

撰文 | JZ
专栏 | 九章算法

题目描述

在一个二维地图上有很多军营,每个军营的座标为(x,y),有一条平行于y轴且长度无限的路,补给车经过这条路时会将每个军营的物资放到离他们军营最近的路边(这条马路所在的位置使得所有军营到达马路的距离和最小),请问所有军营到马路的最短距离和是多少?

在线测评地址:LintCode 领扣

样例

        输入:
[[-10,0],[0,0],[10,0]]
输出:20
说明:假设路在x=0上,最短路径和为10+0+10=20
      

题解

排序,中位数,根据题意,完全可以无视每个点的y座标

所有点到达马路的直线距离为垂直距离,想要让每个点到马路的路程和最小那么马路一定在中位数上。

如果有奇数个点,则马路处于那个电上,如果有偶数个点,马路在中位数的两个端点之间,

复杂度O(nlogn)。

        public class Solution {
    /**
     * @param coordinates: a series of coordinates (x, y)
     * @return: Given a series of coordinates (x, y),return the shortest sum of distance
     */
    public int Fetchsupplies(List<List<Integer>> coordinates) {
        //import Collections;
        List<Integer> tmp = new ArrayList<Integer>();
        for(List<Integer> coordinate : coordinates){
            tmp.add(coordinate.get(0));
        }
        Collections.sort(tmp);
        int size = tmp.size();
        double mid = 0;
        if(size % 2 == 0){
            int l = size / 2 - 1;
            int r = l+1;
            mid = (tmp.get(l) + tmp.get(r)) / 2; 
        }
        else {
            mid = tmp.get((size - 1) / 2);
        }
        double ans = 0;
        for(int i = 0;i < size;i++){
            ans += Math.abs(tmp.get(i) - mid);
        }
        return (int)ans;
    }
}
      

更多语言代码参见:九章算法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章