LeetCode - 774. Minimize Max Distance to Gas Station
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.
贪心肯定不对,参考discuss,假设一个结果,然后对结果进行二分逼近。
public double minmaxGasDist(int[] stations, int K) { int LEN = stations.length; double left = 0, right = stations[LEN - 1] - stations[0], mid = 0; while (right >= left + 0.000001) { mid = right - (right - left) / 2; int cnt = 0; for (int i = 0; i < LEN - 1; i++) { cnt += Math.ceil((stations[i + 1] - stations[i]) / mid) - 1; //重点理解代码,d_i / (cnt_i + 1) <= mid } if (cnt > K) { left = mid; } else { right = mid; } } return mid; }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。








浙公网安备 33010602011771号