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

被折叠的 条评论
为什么被折叠?



