码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 774. Minimize Max Distance to Gas Station

时间:2018-02-18 11:13:54      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:div   space   maximum   asd   .com   gpo   ini   output   note   

原题链接在这里:https://leetcode.com/problems/minimize-max-distance-to-gas-station/description/

题目:

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.

题解:

在0到10^8范围内猜测有这么个distance D. 若是符合要求, 那么每两个station之间的距离除以这个D就是新加的数目. 这些新加的数目和 <= K.

若是如何要求, 可以继续在较小的一侧做 binary search.

Time Complexity: O(nlogW). n = stations.length. W = 10^14. 从10^8范围猜到10^-6范围.

Space: O(1).

AC Java:

 1 class Solution {
 2     public double minmaxGasDist(int[] stations, int K) {
 3         double l = 0;
 4         double r = 1e8;
 5         while(r - l > 1e-6){
 6             double m = l + (r-l)/2.0;
 7             if(possible(stations, K, m)){
 8                 r = m;
 9             }else{
10                 l = m;
11             }
12         }
13         
14         return l;
15     }
16     
17     private boolean possible(int [] stations, int K, double d){
18         int count = 0;
19         for(int i = 0; i<stations.length-1; i++){
20             count += (int)((stations[i+1] - stations[i])/d);
21         }
22         
23         return count <= K;
24     }
25 }

 

LeetCode 774. Minimize Max Distance to Gas Station

标签:div   space   maximum   asd   .com   gpo   ini   output   note   

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/8452521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!