一輛汽車在一條筆直的道路上行駛,一開始有original
單位的汽油。這條筆直的道路上有n
個加油站,第i
個加油站距離汽車出發位置的距離爲distance[i]單位距離,能夠給汽車加apply[i]單位汽油。汽車每行駛1
單位距離會消耗1
單位的汽油,假設汽車的油箱能夠裝無限多的汽油。目的地距離汽車出發位置的距離爲target
,請問汽車可否到達目的地,若是能夠返回最少的加油次數,不然返回-1
。面試
考慮貪心,每次都用能到達而且能加最多油的加油站加油。算法
本題考察了用優先隊列來貪心的思想。對於汽車能到達的加油站,顯然採用能提供油最多的加油站加油,這樣才能保證到達目的地後加油次數最少,這個貪心的思想頗有特點很值得借鑑。bash
www.jiuzhang.com/solution/ga…app
/**
* 本參考程序來自九章算法,由 @華助教 提供。版權全部,轉發請註明出處。
* - 九章算法致力於幫助更多中國人找到好的工做,教師團隊均來自硅谷和國內的一線大公司在職工程師。
* - 現有的面試培訓課程包括:九章算法班,系統設計班,算法強化班,Java入門與基礎算法班,Android 項目實戰班,
* - Big Data 項目實戰班,算法面試高頻題班, 動態規劃專題班
* - 更多詳情請見官方網站:http://www.jiuzhang.com/?source=code
*/
public class Solution {
/**
* @param target: The target distance
* @param original: The original gas
* @param distance: The distance array
* @param apply: The apply array
* @return: Return the minimum times
*/
class Station {
public int d;
public int gas;
public Station(int d, int gas) {
this.d = d;
this.gas = gas;
}
}
public static Comparator<Station> gasComparator = new Comparator<Station>(){
public int compare(Station a, Station b) {
return b.gas - a.gas;
}
};
public static Comparator<Station> dComparator = new Comparator<Station>(){
public int compare(Station a, Station b) {
return a.d - b.d;
}
};
public int getTimes(int target, int original, int[] distance, int[] apply) {
// Write your code here
Queue<Station> q = new PriorityQueue<Station>(distance.length, gasComparator);
Station[] s = new Station[distance.length];
for(int i = 0; i < distance.length; i++) {
s[i] = new Station(distance[i], apply[i]);
}
Arrays.sort(s, dComparator);
int ans = 0;
int i = 0;
while(original < target && i < distance.length) {
while(i < distance.length && original >= s[i].d) {
q.offer(s[i]);
i++;
}
Station now = q.poll();
if(now == null) {
break;
}
original += now.gas;
ans++;
}
if(original >= target) {
return ans;
} else {
return -1;
}
}
}複製代碼