首页 > 代码库 > 【leetcode】Gas Station

【leetcode】Gas Station

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.

Hide Tags
 Greedy
 
注意一点,如果车从0,开到i没有油了,那么我们下一个尝试的点应该为i+1。
因为在0点加了油,开到1时必定有剩余,实际上对于后面的点来说,初始油量是多了的
所以如果从0开始都到不了i,说明0到i之间的任何点都到不了。
 
 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 };

 

【leetcode】Gas Station