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.

思路:首先如何使得每个station之间的最大距离最小,比如:两个station为[1, 9],间隔为8。要插入一个station使得最大距离最小,插入后应该为[1, 5, 9],最大间隔为4。如果插入后为[1, 6, 9], [1, 3, 9],它们的最大间隔分别为5, 6,不是最小。可以看出,对于插入k个station使得最大间隔最小的唯一办法是均分。

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

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

解法1: 优先队列,每次找出gap最大的一个区间,然后新加入一个station,直到所有的k个station都被加入,此时最大的gap即为所求。采用优先队列,使得每次最大的gap总是出现在队首。空间复杂度是O(n),时间复杂度是O(klogn),其中k是要加入的新station的个数,n是原有的station个数。这种方法应该没毛病,但是TLE

解法:二分法,判定条件不是简单的大小关系,而是根据子函数。minmaxGap的最小值left = 0,最大值right = stations[n - 1] - stations[0]。每次取mid为left和right的均值,然后计算如果mimaxGap为mid,那么最少需要添加多少个新的stations,记为count。如果count > K,说明均值mid选取的过小,必须新加更多的stations才能满足要求,更新left的值;否则说明均值mid选取的过大,使得需要小于K个新的stations就可以达到要求,寻找更小的mid,使得count增加到K。如果假设stations[N- 1] - stations[0] = m,空间复杂度是O(1),时间复杂度是O(nlogm),可以发现与k无关。

Java:

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:

class Solution(object):
def minmaxGasDist(self, stations, K):
"""
:type stations: List[int]
:type K: int
:rtype: float
"""
def possible(stations, K, guess):
return sum(int((stations[i+1]-stations[i]) / guess)
for i in xrange(len(stations)-1)) <= K left, right = 0, 10**8
while right-left > 1e-6:
mid = left + (right-left)/2.0
if possible(mid):
right = mid
else:
left = mid
return left  

Python:

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  

Python:

class Solution(object):
def minmaxGasDist(self, stations, K):
"""
:type stations: List[int]
:type K: int
:rtype: float
"""
stations.sort()
step = 1e-9
left, right = 0, 1e9
while left <= right:
mid = (left + right) / 2
if self.isValid(mid, stations, K):
right = mid - step
else:
left = mid + step
return mid
def isValid(self, gap, stations, K):
for x in range(len(stations) - 1):
dist = stations[x + 1] - stations[x]
K -= int(math.ceil(dist / gap)) - 1
return K >= 0  

C++:

class Solution {
public:
double minmaxGasDist(vector<int>& stations, int K) {
double left = 0, right = 1e8;
while (right - left > 1e-6) {
double mid = left + (right - left) / 2;
if (helper(stations, K, mid)) right = mid;
else left = mid;
}
return left;
}
bool helper(vector<int>& stations, int K, double mid) {
int cnt = 0, n = stations.size();
for (int i = 0; i < n - 1; ++i) {
cnt += (stations[i + 1] - stations[i]) / mid;
}
return cnt <= K;
}
};

C++:

class Solution {
public:
double minmaxGasDist(vector<int>& stations, int K) {
double left = 0, right = 1e8;
while (right - left > 1e-6) {
double mid = left + (right - left) / 2;
int cnt = 0, n = stations.size();
for (int i = 0; i < n - 1; ++i) {
cnt += (stations[i + 1] - stations[i]) / mid;
}
if (cnt <= K) right = mid;
else left = mid;
}
return left;
}
};

  

  

类似题目:

719. Find K-th Smallest Pair Distance

668. Kth Smallest Number in Multiplication Table

644. Maximum Average Subarray II

378. Kth Smallest Element in a Sorted Matrix

All LeetCode Questions List 题目汇总

[LeetCode] 774. Minimize Max Distance to Gas Station 最小化加油站间的最大距离的更多相关文章

  1. [LeetCode] Minimize Max Distance to Gas Station 最小化去加油站的最大距离

    On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., statio ...

  2. LeetCode - 774. Minimize Max Distance to Gas Station

    On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., statio ...

  3. 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], ..., statio ...

  4. leetcode 刷题之路 68 Gas Station

    There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...

  5. 贪心:leetcode 870. Advantage Shuffle、134. Gas Station、452. Minimum Number of Arrows to Burst Balloons、316. Remove Duplicate Letters

    870. Advantage Shuffle 思路:A数组的最大值大于B的最大值,就拿这个A跟B比较:如果不大于,就拿最小值跟B比较 A可以改变顺序,但B的顺序不能改变,只能通过容器来获得由大到小的顺 ...

  6. [LeetCode] Gas Station

    Recording my thought on the go might be fun when I check back later, so this kinda blog has no inten ...

  7. leetcode@ [134] Gas station (Dynamic Programming)

    https://leetcode.com/problems/gas-station/ 题目: There are N gas stations along a circular route, wher ...

  8. [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。

    LeetCode上 Gas Station是比较经典的一题,它的魅力在于算法足够优秀的情况下,代码可以简化到非常简洁的程度. 原题如下 Gas Station There are N gas stat ...

  9. [LeetCode] Gas Station 加油站问题

    There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...

随机推荐

  1. c++练手项目:英语单词拼写测试程序

    代码比较简单.基本的思路是从文本文件中按行读取数据,数据结构为“hello-你好”.前面是英语,后面是中文,中间用“-”连接.程序通过查找连词符的位置来分割中文和英文.再通过和用户输入的单词进行比较判 ...

  2. Spring boot集成Swagger2,并配置多个扫描路径,添加swagger-ui-layer

    Spring boot集成Swagger,并配置多个扫描路径 1:认识Swagger Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目 ...

  3. 弹性盒模型:flex多行多列两端对齐,列不满左对齐

    [1]需求: [2]解决方案: 最近遇到布局上要求item两端对齐,且最后一行在列不满的情况下要求左对齐,使用flex的justify-content: space-between;实现时发现最后一行 ...

  4. Python获取当前脚本文件夹(Script)的绝对路径

    Python获取当前脚本绝对路径 Python脚本有一个毛病,当使用相对路径时,被另一个不同目录下的py文件中导入时,会报找不到对应文件的问题.感觉是当前工作目录变成了导入py文件当前目录.如果你有配 ...

  5. java的新生代 老年代 永久代

    介绍得非常详细: 新生代回收:(复制算法) 在堆中,新生代主要存放的是哪些很快就会被GC回收掉的或者不是特别大的对象(是否设置了-XX:PretenureSizeThreshold 参数).复制算法的 ...

  6. api的url规则设计,带参数的路由

    api的url设计规则 router := gin.Default() router.GET("/topic/:topic_id", func(context *gin.Conte ...

  7. (尚023)Vue_案例_交互添加

    最终达到效果: 1.做交互,首先需要确定操作哪个组件? 提交------操作组件Add.vue 2.从哪开始做起呢? 从绑定事件监听开始做起,确定你跟谁绑定事件监听,在回调函数中做什么, ====== ...

  8. tldr/cheat

    tldr 比man好用的查询命令查询工具, man很强大,但是 TLDR,too long dont read 安装 npm install -g tldr 使用说明 其他版本下载 https://g ...

  9. CSS链接伪类:超链接的状态

    一.状态: a:link{属性:值;} 链接默认状态 a:visited{属性:值;} 链接访问之后的状态 a:hover{属性:值;} 鼠标放到链接上显示的状态 a:active{属性:值;} 链接 ...

  10. 记一次CDH集群日志数据清理

    背景 集群运行一段时间(大概一月多)后,cloudera manager管理界面出现爆红,爆红的组件有hdfs.zookeeper. 发现问题 点击详细内容查看,报日志空间不够的错误.初步判断是各个组 ...