[Leetcode]Gas Station

来源:互联网 发布:中国木制品数据 编辑:程序博客网 时间:2024/06/03 19:51

There are N gas stations along a circular route, where the amount of gas at stationi is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from stationi 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.


class Solution {public:    /*algorithm:       for each start index,check whether it can reach full         time O(n*n), TLE error    */    bool canTravel(vector<int>& gas, vector<int>& cost,int start){        int sum = 0,n = gas.size();        for(int i=0;i < n;i++){            sum += gas[start] - cost[start];            if(sum < 0)return false;            start = (start+1)%n;        }        return true;    }    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {        int index = -1;        for(int i = 0;i < gas.size();i++){            if(canTravel(gas,cost,i)){                index = i;                break;            }        }        return index;    }};

class Solution {public:    /*algorithm:greedy    time O(n)    */    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {        int index = 0;        int sum = 0,n = gas.size(),total=0;        for(int i = 0;i < n;++i){            sum += gas[i] - cost[i];            total += gas[i] - cost[i];            if(sum < 0){                index = (i+1)%n;                sum = 0;            }        }        return total >= 0?index:-1;    }};


0 0