class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (gas.size() != cost.size()) return -1;
        
        vector<int> diff;
        int total = 0;
        for (int i = 0; i < gas.size(); i++){
            
            int tmp = gas[i] - cost[i];
            total += tmp;
            diff.push_back(tmp);
        }
        if (total < 0) return -1;
        
        int cum = 0;
        int index = 0;
        
        for (int i = 0; i < diff.size(); i++){
            
            cum += diff[i];
            if (cum < 0){
                index = i+1;
                cum = 0;
            }
        }
        return index;
    }
};

 

posted on 2013-10-27 12:36  tanghulu321  阅读(227)  评论(0编辑  收藏  举报