[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.

暴力解法为o(N^2),没有通过。想了一下,如果汽车从A点出发,运行到B点,发现油的余量无法抵达下一个点的话,那我们就直接从下一个点出发,开始尝试解。这样的复杂度为o(N)。因为任何从A点和B点出发的尝试都不会使车越过B点。

class Solution {
    public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        for(int startIdx = 0; startIdx < gas.size(); ){
            int currentIdx = startIdx;
            int gasInTank = 0;
            bool isBegin = true;
            while(true){
                if(currentIdx == startIdx && isBegin != true){
                    return startIdx;
                }
                else{
                    isBegin = false;
                    gasInTank += gas[currentIdx] - cost[currentIdx];
                    if(gasInTank < 0){
                    //if gas is not enough, if we have go over one round, return -1
                        if(currentIdx < startIdx || currentIdx == gas.size() - 1){
                            return -1;
                        }
                        else{
                            startIdx = currentIdx + 1;
                            break;
                        }
                    }
                    else{
                        currentIdx++;
                        if(currentIdx == gas.size()){
                            currentIdx = 0;
                        }
                    }
                }
            }
        }
    //no suitable station is found
    return -1;
    }
};

运行结果

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.