原題鏈接在這里:https://leetcode.com/problems/minimize-max-distance-to-gas-station/description/
題目:
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.lengthwill be an integer in range[10, 2000].stations[i]will be an integer in range[0, 10^8].Kwill be an integer in range[1, 10^6].- Answers within
10^-6of the true value will be accepted as correct.
題解:
在0到10^8范圍內猜測有這么個distance D.
若是符合要求, 那么每兩個station之間的距離除以這個D取整數就是新加油站的數目.
這些新加的數目和若是<= K, it means that distance is big enough. Think like this, if it is able to add j <= K gas stations to get achieve this distance. Than add K-j more just make the distance even smaller.
所以可以繼續在較小的一側做 binary search to find a smaller D.
Time Complexity: O(nlogW). n = stations.length. W = 10^14. 從10^8范圍猜到10^-6范圍.
Space: O(1).
AC Java:
1 class Solution { 2 public double minmaxGasDist(int[] stations, int K) { 3 double l = 0; 4 double r = 1e8; 5 while(r - l > 1e-6){ 6 double m = l + (r-l)/2.0; 7 if(possible(stations, K, m)){ 8 r = m; 9 }else{ 10 l = m; 11 } 12 } 13 14 return l; 15 } 16 17 private boolean possible(int [] stations, int K, double d){ 18 int count = 0; 19 for(int i = 0; i<stations.length-1; i++){ 20 count += (int)((stations[i+1] - stations[i])/d); 21 } 22 23 return count <= K; 24 } 25 }
類似Koko Eating Bananas, Capacity To Ship Packages Within D Days.
