1. 程式人生 > >Leetcode 774. Minimize Max Distance to Gas Station

Leetcode 774. Minimize Max Distance to Gas Station

Problem:

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.

Solution:

  這道題是用了一種非常規的Binary Search解法。最開始我想用一種貪心演算法,每次找出間隔最大的兩站然後做二分,但這個思路是不對的,比如1,7,K等於2時,如果做二分的話會在4,2.5的位置依次放兩站,其結果為3,而實際上只需要在3,5依次放兩站其結果為2。因此這個演算法不正確。答案用的是一種非常巧妙的二分搜尋,二分搜尋的是當最大間距為pivot時,需要放置的station的數量。如果需要放置的數量大於K,說明pivot值過小,需要在pivot和right之間繼續尋找這個最大間距,否則在left和pivot中二分查詢。最後得到的結果就是在放置K個station時最小化的最大間距。這道題和我們的常規想法不同,平時對於一般的問題,我們都是根據已知條件去計算這個結果,而這道題算是逆向思維,它先假設一個結果然後去判斷其是否滿足條件。這也是這道題評為hard的原因吧。

Code:

 

 1 class Solution {
 2 public:
 3     double minmaxGasDist(vector<int>& stations, int K) {
 4         double left = 0;
 5         double right = stations.back()-stations[0];
 6         while(right-left > 1e-6) {
 7             double pivot = left+(right-left)/2;
 8             int count = 0;
 9             for(int i = 1;i != stations.size();++i){
10                 count += (stations[i]-stations[i-1])/pivot;
11             }
12             if(count <= K)
13                 right = pivot;
14             else
15                 left = pivot;
16         }
17         return left;
18     }
19 };