首页 > 代码库 > 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.

 

方法一:直接暴力破解,枚举以每个加油站为起点,时间复杂度为O(n2),空间复杂度为O(1)
方法二:由于车开始时是空油箱而且是无限空间,故其每到一个加油站必加满油,如果油箱内油够到下一个加油站,那就可以继续前行。故我们可以构造一个差值数组。
gas[0]gas[1]gas[2]gas[3]
cost[0]cost[1]cost[2]cost[3]
remain[0]remain[1]remain[2]remain[3]
 
 
 
 
remain[i]表示从加油站i到加油站(i+1)%n车还剩多少油,要让车可以走一圈,那么必须从 j 加油站开始,j需要满足remain[j] >= 0 且 累加右面的remain元素的和都需要为非负值
 1 class Solution { 2 public: 3     int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { 4         vector<int> remain(gas.size(), 0); 5         for(int i=0; i<remain.size(); ++i) 6             remain[i] = gas[i]-cost[i]; 7         int start = 0; 8         int sum = 0; 9         int total = 0;  //统计整个remian的和10         for(int i=0; i<remain.size(); ++i) {11             total += remain[i];12             sum += remain[i];13             if( sum < 0 ) { //如果sum为0,表明前面的连续子序列和为负数,需要重新另选起点14                 start = i+1;15                 sum = 0;16             }17         }18         return ( (total < 0) ? -1 : start );    //若total为负数,说明不可能完成19     }20 };