LeetCode _ 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.

思路: 类似KMP不回朔的思想。start表示开始的点,sum表示当前汽车的油量。当汽车到达汽油站i时如果不能到达下一站,则更新start直到可以使汽车能够从当前节点到达下一站,如果不存在,则把start设置为下一站。

class Solution {

public:

    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {

       int len = gas.size();

       if(cost.size() != len) return -1;

       vector<int> flag(len*2, 0);

       for(int i = 0; i< len; i++)

            flag[i] = gas[i] - cost[i];

       for(int i = len ; i< len *2; ++i)

            flag[i] = flag[i-len];

    

       int start = 0 , sum = 0;         

       for(int i = 0; i< len + start && start < len; )

        {

            sum += flag[i] ;

            if(sum >= 0){

                ++i;

                continue;

            } 

            while(sum< 0 && start < i){

                sum -= flag[start];

                ++start;

            }

            i++;

            if(sum < 0){

                sum = 0;

                start = i;

            }

            

        }

        if(start <len)

         return start;

        return -1;

        

    }

};

 

你可能感兴趣的:(LeetCode)