前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Minimize Max Distance to Gas Station

Minimize Max Distance to Gas Station

作者头像
用户1147447
发布2019-05-26 00:30:09
6130
发布2019-05-26 00:30:09
举报
文章被收录于专栏:机器学习入门

LWC 69: 774. Minimize Max Distance to Gas Station

Problem:

On a horizontal number line, we have gas stations at positions stations[0], stations1, …, 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.

思路: 首先求出每个station之间的距离,考虑如下问题:两个station为[1, 9],gap为8。要插入一个station使得最大的最小,显然插入后应该为[1, 5, 9],最大间隔为4。举个反例,如果插入后为[1, 6, 9], [1, 3, 9],它们的最大间隔分别为5, 6,明显不是最小。从这里可以看出,对于插入k个station使得最大的最小的唯一办法是均分。

一种贪心的做法是,找到最大的gap,插入1个station,依此类推,但很遗憾,这种贪心策略是错误的。问题的难点在于我们无法确定到底哪两个station之间需要插入station,插入几个station也无法得知。

换个思路,如果我们假设知道了答案会怎么样?因为知道了最大间隔,所以如果目前的两个station之间的gap没有符合最大间隔的约束,那么我们就必须添加新的station来让它们符合最大间隔的约束,这样一来,对于每个gap我们是能够求得需要添加station的个数。如果需求数<=K,说明我们还可以进一步减小最大间隔,直到需求数>K。

Java版本:

代码语言:javascript
复制
   public double minmaxGasDist(int[] stations, int K) {
        int n = stations.length;
        double[] gap = new double[n - 1];
        for (int i = 0; i < n - 1; ++i) {
            gap[i] = stations[i + 1] - stations[i];
        }
        double lf = 0;
        double rt = Integer.MAX_VALUE;
        double eps = 1e-7;
        while (Math.abs(rt - lf) > eps) {
            double mid = (lf + rt) /2;
            if (check(gap, mid, K)) {
                rt = mid;
            }
            else {
                lf = mid;
            }
        }
        return lf;
    }

    boolean check(double[] gap, double mid, int K) {
        int count = 0;
        for (int i = 0; i < gap.length; ++i) {
            count += (int)(gap[i] / mid);
        }
        return count <= K;
    }

Python版本:

代码语言:javascript
复制
class Solution(object):
    def minmaxGasDist(self, st, K):
        """
        :type stations: List[int]
        :type K: int
        :rtype: float
        """
        lf = 1e-6
        rt = st[-1] - st[0]
        eps = 1e-7
        while rt - lf > eps:
            mid = (rt + lf) / 2
            cnt = 0
            for a, b in zip(st, st[1:]):
               cnt += (int)((b - a) / mid)
            if cnt <= K: rt = mid
            else: lf = mid
        return rt
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年01月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 69: 774. Minimize Max Distance to Gas Station
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档