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

1 如果总的gas - cost小于零的话,那么没有解返回-1。(总gas> 总cost 是有解的充分便要条件,要是解这道题的关键)

2 如果前面所有的gas - cost加起来小于零,那么前面所有的点都不能作为出发点(存在gas-cost<0,剩下的必然存在gas-cost>0)。

3 选择最佳出发点后,判断从这点出发能否环行一圈。

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int len = gas.size();
        int res = -1;
        int res_gas = 0;
        int start_station = 0;
        int total_res = 0;
        for(int i =0 ; i < len; i++)
        {
            res_gas += (gas[i] - cost[i]) ;
            total_res += (gas[i] - cost[i]) ;
            if(res_gas < 0)
            {
                start_station = i+1;
                res_gas = 0;
            }
        }
        if(total_res >= 0)
        {
            res = start_station;
        }
        return res;
        
    }
};

  

原文地址:https://www.cnblogs.com/qiaozhoulin/p/4551914.html