zoukankan      html  css  js  c++  java
  • LC 774. Minimize Max Distance to Gas Station 【lock,hard】

    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:

    1. stations.length will be an integer in range [10, 2000].
    2. stations[i] will be an integer in range [0, 10^8].
    3. K will be an integer in range [1, 10^6].
    4. Answers within 10^-6 of the true value will be accepted as correct.

    也是用了二分查找,找的是中位数。

    Runtime:28ms  Beats: 81.77%

    class Solution {
    public:
        double minmaxGasDist(vector<int>& stations, int K) {
            double left = 0.0, right = 1000000.0, mid = 0.0;
            while (left + 0.0000001 < right) {
                mid = left + (right - left) / 2.0;
                int cnt = 0;
                for (int i = 0; i < stations.size() - 1; i++) {
                    cnt += (stations[i + 1] - stations[i]) / mid;
                }
                if (cnt <= K) right = mid;
                else left = mid;
            }
            return left;
        }
    };
  • 相关阅读:
    简单的运动框架——分享给初学者
    Python数据分析学习日志(1. 书单)
    mysql恢复数据参考
    window cmd 杀掉 java.exe 进程
    转载: Ajax关于readyState和status的讨论
    开发问题bug记录
    vue基础part10
    vue基础part9
    vue基础part(7-8)
    vue基础part(4-6)
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10156331.html
Copyright © 2011-2022 走看看