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个圈里面有N个汽油站,i站的汽油有gas[i]汽油。现在有1辆无穷容量油箱的车,它从i站开到(i+1)需要耗费cost[i]汽油。如果这辆车可以走完这个圈,那末返回这个车的出发点,否者返回⑴.
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start=0,tank=0,total=0;
for(int i=0;i<gas.size();i++)
{
tank+=gas[i]-cost[i];
if(tank<0)
{
total+=tank;
tank=0;
start=i+1;
}
}
return ((total+tank)<0)?-1:start;
}
};
上一篇 mysql数据入门管理
下一篇 数据结构:平衡二叉树(AVL树)