撰文 | 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;
}
}
更多語言代碼參見:九章算法