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 ;
}
}