69 - 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.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.

Code in C++:

double minmaxGasDist(vector<int>& st, int K) {
    int count, N = st.size();
    float left = 0, right = st[N - 1] - st[0], mid;
    while (left + 0.00001 < right) {
        mid = (left + right) / 2;
        count = 0;
        for (int i = 0; i < N - 1; ++i)
            count += ceil((st[i + 1] - st[i]) / mid) - 1;
        if (count > K) left = mid;
        else right = mid;
    }
    return right;
}

注解:
二分法:
1)left=0,right=已有的站从头到尾的总距离,left+0.00001<right时结果满足要求。
2)mid=(left+right)/2,计算以此mid作为最大间距时两站之间需要插入几个点,若大于K,说明mid取小了,令left=mid,反之令right=mid。

Discuss地址:
https://discuss.leetcode.com/category/1739/minimize-max-distance-to-gas-station

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • rmdir是常用的命令,该命令的功能是删除空目录,一个目录被删除之前必须是空的。(注意,rm – r dir命令可...
    很少更新了阅读 3,345评论 0 0
  • 心动更要行动 做好一件事,要有责任心,执行力。
    贤慧_8c12阅读 1,501评论 0 0