LWC 69: 774. Minimize Max Distance to Gas Station
2018-01-29 14:36
357 查看
LWC 69: 774. Minimize Max Distance to Gas Station
传送门:774. Minimize Max Distance to Gas StationProblem:
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版本:
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, 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
相关文章推荐
- [Leetcode] 774. Minimize Max Distance to Gas Station 解题报告
- [LeetCode] 774. Minimize Max Distance to Gas Station 最小化加油站间的最大距离
- LeetCode - 774. Minimize Max Distance to Gas Station
- LeetCode 774. Minimize Max Distance to Gas Station
- LWC 68: 769. Max Chunks To Make Sorted (ver. 1)
- how to delte minimize and max button in right upper!
- how to delte minimize and max button in right upper!
- [leetcode] Gas Station
- PAT 1072. Gas Station
- hdu 1081 To The Max
- POJ 1050 to the max
- ACM学习-POJ-1050-To the Max
- leetcode:Gas Station 【Java】
- To The Max(dp思想)
- POJ 1050 To the Max
- POJ 1050 To the Max 最大子矩阵和 简单dp
- undefined reference to `omp_get_max_threads'
- LeetCode Gas Station
- Leetcode-134-Gas Station C#
- LeetCode--gas-station