LeetCode 134.加油站
程序员文章站
2024-03-11 11:11:19
...
题目描述
代码
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int index = -1;
int gasofcar = 0;
for(int i = 0;i<n;i++){
gasofcar = gas[i];
for(int j = i+1;j<=n;j++){
j = j%n;
if(j == 0) gasofcar = gasofcar - cost[n-1];
else gasofcar = gasofcar - cost[j-1];
if(j == i) {
if(gasofcar >= 0) index = i;
break;
}
if(gasofcar < 0) break;
gasofcar += gas[j];
}
}
return index;
}
};