LeetCode OJ:Gas Station

1900 ワード

Gas Station  
Total Accepted: 5589 
Total Submissions: 23851 My Submissions
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]-cost[i]を考慮対象とし、この問題はこの点からずっとその点に加算できる前の点を見つけることであり、その中に0未満の点は現れない.1つの比較的率直な方法は、各点をこのように探して答えを確定することである.実際には、これらの点の和sum>=0があれば、必ず問題を満たす点を見つけることができることを示している.それなら、
シーケンスa 1,a 2,a 3を仮定すると.....ai,a(i+1)....an,a 1+a 2+..+ai<0の場合、必然的にa(i+1)+..+an>0(sum>=0を満たさない場合)および|a(i+1)+..+an|>=|a1+a2+...+ai|では、sumと最小の点の後の点を見つけるだけで、必然的に満足することができます.この点から、sum>=0を保証することができます.
class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int sum=0;
        int index=0,val=0;
        for(int i=0;i<gas.size();i++){
            sum+=gas[i]-cost[i];
            if(sum<val){
                val=sum;
                index=i+1;
            }
        }
        if(sum>=0){
            return index%gas.size();
        }
        return -1;
    }
};

answer2
class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int total=0;
        int j=-1;
        for(int i=0,sum=0;i<gas.size();++i){
            sum+=gas[i]-cost[i];
            total+=gas[i]-cost[i];
            if(sum<0){
                j=i;
                sum=0;
            }
        }
        return total>=0?j+1:-1;
    }
};