[Leetcode] 134. Gas Station 解题报告

xiaoxiao2021-02-27  272

题目:

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note: The solution is guaranteed to be unique.

思路:

刚开始的时候一头雾水,后来知道了采用贪心策略可以解答,但是仍然没有想明白为什么。参考了网上的代码才豁然开朗下面我试着解释一下:

remainingGas表示截止当前,邮箱中总共结余的油量,resultIndex表示我们应该出发的位置,而sum表示从resultIndex开始环行,截止当前剩余的油量。然后我们就顺次遍历每个加油站,更新remainingGas和sum。一旦发现sum小于0,说明从resultIndex开始无法到达该站,所以我们试着从当前站开始出发,所以更新sum和resultIndex。最后我们判断remaingGas是否小于0,如果小于0,说明跑完一圈能加的油量小于所需要消耗的油量,所以无解;否则就返回resultIndex。

关键在于正确性证明:

1)如果从头开始,每次累计剩下的油量都为正数,那么没有问题,可以从头开始到结束。

2)如果到中间某个位置,剩余的油量为负了,那么说明之前累积剩余的油量不够从这一站到下一站了,那么就从下一站重新开始计数。为什么是下一站,而不是之前的某一站呢?因为第一站剩余的油量肯定是大于等于0的,然而到当前一站的油量变负了,说明从第一站之后开始的话到当前油量只会更少而不会增加,也就是说,从第一站之后,当前站之前的某站出发到当前站剩余的油量是不可能大于0的。所以只能从下一站重新出发开始计算剩余的油量,并且把之前欠下的油量也累加起来,看到最后剩余的油量是不是大于欠下的油量。

代码:

class Solution { public:     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {         int remainingGas = 0;         int resultIndex = 0;         int sum = 0;         for(size_t i = 0; i < gas.size(); ++i) {             remainingGas += gas[i] - cost[i];             sum += gas[i] - cost[i];             if(sum < 0) {                 sum = 0;                 resultIndex = i + 1;             }         }         if(remainingGas < 0) {             return -1;         }         else {             return resultIndex;         }     } };

转载请注明原文地址: https://www.6miu.com/read-5011.html

最新回复(0)