On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., stations[N-1]
, where N = stations.length
.
Now, we add K
more gas stations so that D, the maximum distance between adjacent gas stations, is minimized.
Return the smallest possible value of D.
Example:
Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9
Output: 0.500000
Note:
stations.length
will be an integer in range[10, 2000]
.stations[i]
will be an integer in range[0, 10^8]
.K
will be an integer in range[1, 10^6]
.- Answers within
10^-6
of the true value will be accepted as correct.
思路:就是如果加入0個station,那麼上限就是現在的max adjcent distance, 如果加入無窮多個station,那麼下限就是distance = 0;
那麼就是要找到恰當的dis 使得加入的station是K,那麼就是個二分答案的binary search,輔助方程是求給你distance,求要加入多少個stations. 求station 個數就用station[i + 1] - station[i] / dis
注意double的判斷,不用用start + 1 < end,要用eps = 1e-5 , start + eps < end來判斷;
class Solution {
public double minmaxGasDist(int[] stations, int K) {
if(stations == null || stations.length == 0) {
return 0.0;
}
double maxdis = 0;
for(int i = 0; i < stations.length - 1; i++) {
maxdis = Math.max(maxdis, stations[i + 1] - stations[i]);
}
double start = 0; double end = maxdis;
double eps = 1e-5;
while(start + eps < end) {
double mid = start + (end - start) / 2;
if(needstation(stations, mid) > K) {
start = mid;
} else {
end = mid;
}
}
if(needstation(stations, start) > K) {
return end;
}
return start;
}
private int needstation(int[] stations, double dis) {
int count = 0;
int i = 0;
while(i < stations.length - 1) {
count += (stations[i + 1] - stations[i]) / dis;
i++;
}
return count;
}
}