当前位置:网站首页>[daily question] 871 Minimum refueling times

[daily question] 871 Minimum refueling times

2022-07-04 17:59:00 Wang Liuliu's it daily

871. Minimum refueling times
Difficult questions
Reference resources :【 Gongshui Sanye 】 Simple priority queue ( Pile up ) Greedy question
Topic ideas :
- The gas stations on the road As Barrels of oil , Every time I pass , Just take the oil and put it in the trunk ;
- When there is not enough oil , Take out what you have in the trunk The largest barrel of oil Fill the oil tank
- Since then , If the oil in the tank and the trunk are not enough , Then it won't arrive

class Solution {
    
    public int minRefuelStops(int target, int startFuel, int[][] stations) {
    
        //  Use priority queues , Load the oil passing through the gas station 
        PriorityQueue<Integer> q = new PriorityQueue<>((o1, o2) -> (o2 - o1));
        int ans = 0, len = stations.length;
        //  Special judgement :
        if (len < 1) return startFuel < target ? -1 : 0;
        int fuel = startFuel;//  The oil added into the tank ( Including used )
        //  Pass all the gas stations you can reach , The oil on your back 
        for (int i = 0; i < len; i ++) {
    
            while (fuel < stations[i][0]) {
    
                Integer add = q.poll();
                if (add == null) return -1;
                fuel += add;
                ans ++;
            }
            q.offer(stations[i][1]);
        }
        //  We have passed all the gas stations and still haven't arrived , What's left in the car's fuel tank and trunk fuel, Expect to arrive 
        while (fuel < target) {
    
            Integer add = q.poll();
            if (add == null) return -1;
            fuel += add;
            ans ++;
        }
        return ans;
    }
}
原网站

版权声明
本文为[Wang Liuliu's it daily]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041602494944.html