标签:
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 5 6 int total_oil=0; 7 int index=0; 8 int n=gas.size(); 9 10 11 12 for(int i=0;i<n;i++) 13 { 14 total_oil+=gas[i]; 15 total_oil-=cost[i]; 16 17 if(total_oil<0) 18 { 19 total_oil=0; 20 index=i+1; 21 } 22 } 23 24 //如果循环到了最后一个,没了油,说明任何点都没有希望到达了 25 if(index==n) 26 { 27 return -1; 28 } 29 30 //如果一直循环到最后,仍然有油,说明从0点可以遍历整个路径 31 if(index==0) 32 { 33 return 0; 34 } 35 36 //如果开到最后还剩油,我们继续往后计算。 37 for(int i=0;i<n;i++) 38 { 39 total_oil+=gas[i]; 40 total_oil-=cost[i]; 41 42 //又回到了初始点,则说明从该点可以遍历整个路径 43 if(i==index) 44 { 45 return i; 46 } 47 48 //如果在中间任何一点没有了油,就不必再尝试了 49 if(total_oil<0) 50 { 51 break; 52 } 53 } 54 55 56 return -1; 57 } 58 };
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4251663.html