Leetcode Gas Station

OpenSoucre發表於2014-06-19

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.

此題題目意思是從環型加油站中選擇一個加油站出發,使其能夠回到起始點。

最基本的方法是暴力,用一個二重迴圈解決

本題考慮到汽車到達一個加油加上gas[i]的油,行走到下一個加油站時,剩下的油為gas[i]-cost[i]

首先判斷所有的sum(gas[0..n))是否大於sum(cost[0..n))的和

 如果小於的話,說明不可能有剩餘的油,不可能對每個環形加油站都走一遍,故返回-1

如果大於等於的話,說明存在可能走完所有環形加油站

  累積每個加油站加油行走後剩餘的油即sum(gas[i]-cost[i]),標記初始索引

  如果sum < 0說明從標記索引不可能走到,故重新標記一下一個索引,重新計數知道迴圈結束,返回標記索引

int canCompleteCircuit(vector<int>& gas, vector<int> &cost){
    vector<int> leave(gas.size(),0);
    transform(gas.begin(),gas.end(),cost.begin(), leave.begin(),minus<int>());
    if(accumulate(leave.begin(),leave.end(),0) < 0) return -1;
    int sum = 0, index = 0;
    for(int i = 0; i < leave.size(); ++ i){
        sum+=leave[i];
        if(sum < 0) sum = 0,index = i+1;
    }
    return index;
}

 

相關文章