1323 · Fetch supplies取物资

该博客讨论了一个二维军事地图上,供应车辆沿垂直轴无限长道路行驶,为各个军事营地配送物资的问题。算法的目标是计算出从所有营地到这条道路的最短总距离。解决方案中提供了一个名为`Fetchsupplies`的方法,该方法根据营地坐标计算出中位数距离,并求出所有营地到中位数距离的绝对值之和,从而得出最短总距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1323 · Fetch supplies取物资

Description
There are many military camps on a two-dimensional map. The coordinates of each military camp are (x, y). There is a road parallel to the y axis and of unlimited length. When the supply vehicle passes this road, the materials of each military camp will be placed The roadside closest to their barracks(The location of this road makes the distance and minimum distance from all military camps to the road),What is the shortest distance from the military camps to the road.

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) {
        // write your code here
        int sum = 0 ;
        if(coordinates == null ){
            return 0 ;
        }
        List<Integer> temp = new ArrayList<Integer>() ;
        for(List<Integer> coordinate : coordinates ){
            temp.add(coordinate.get(0)) ;
        }
        Collections.sort(temp) ;
        int n = temp.size() ;
        int mid = 0 ;
        if(n % 2 == 0){
           mid = (temp.get(n / 2 - 1) + temp.get(n / 2 )) / 2 ;
        }else{
           mid = (temp.get((n-1) / 2 )) / 2 ;
        }
        for(int i = 0 ; i < coordinates.size() ; i++){
            sum +=Math.abs(coordinates.get(i).get(0) - mid) ;
        }
        return sum ;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值