class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { //这个题目有两个问题需要解决 //①:加油车是否能够走完一圈:一次循环把花费的汽油和加入的汽油进行加减,如果大于0可以,否则不可以。 //②:在哪个位置起始能够走完一圈:对每一个加油站设置一个变量diff,cost(路上总共花费的)-gas(已经有的) = diff。如果每个站点的diff都是 //costs表示每一个经过每个加油站剩余的油,当油不足以到达下一个加油站的时候,从当前加油站重新计算。前面的加油站都不符合要求 //total表示总共的经过所有加油站剩余的油 int costs = 0; int index = -1; int total = 0; int distance = gas.size(); for (int i=0; i<distance; i++){ costs += gas[i] - cost[i]; total += gas[i] - cost[i]; if (costs < 0){ index = i; costs = 0; } } if (total < 0) return -1; else return index+1 ; } };
原文:http://www.cnblogs.com/Kobe10/p/6351310.html