Gas Station

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.

分析:一开始以为可以正方向和反方向进行讨论,通过几次提交发现,原来只需要考虑正方向,而且每组输入只有一个解

以下为错误解法。

 1 class Solution {
 2 public:
 3     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
 4         if(gas.size() == 1) return gas[0] >= cost[0] ? 0 : -1;
 5         
 6         for(int i = 0; i < gas.size(); i++){
 7             if(positive(gas, cost, i) || reverse(gas, cost, i)) return i;
 8         }
 9         return -1;
10     }
11     bool positive(vector<int> gas, vector<int> cost, int k){
12         int currentGas = 0;
13         for(int i = k; i < gas.size() + k; i++){
14             int index = i % gas.size();
15             currentGas += gas[index] - cost[index];
16             if(currentGas < 0) return false;
17         }
18         return true;
19     }
20     bool reverse(vector<int> gas, vector<int> cost, int k){
21         int currentGas = 0;
22         for(int i = k; i > k - gas.size(); i--){
23             int index = (i + gas.size()) % gas.size();
24             int index1 = (i - 1 + gas.size()) % gas.size();
25             currentGas += gas[index] - cost[index1];
26             if(currentGas < 0) return false;
27         }
28         return true;
29     }
30 };
View Code

由于如果能从结点i到结点j,那么从i+1可能能到j,可能不能到j。但是如果从结点i不能到结点j,那么从结点i+1之后的点都不能到j,因为i~i+1这一段路油箱至少会有剩余,否则不能从i开到i+1。所以,如果从点i开始计算的话,那么下一个该计算的点就是j。

运行时间:8ms

 1 class Solution {
 2 public:
 3     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
 4         int current = 0, whole = 0, result = 0;
 5         for(int i = 0; i < gas.size(); i++){
 6             current += gas[i] - cost[i];
 7             whole += gas[i] - cost[i]; //to judge whether result is valid
 8             if(current < 0){
 9                 current = 0;
10                 result = i + 1;
11             }
12         }
13         return whole < 0 ? -1 : result;
14     }
15 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4504893.html