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.
int n = gas.size();
int curSum = 0;
int total = 0;
int pos = 0;
for(int i = 0; i < n; ++i)
{
int curRemain = gas[i]-cost[i];
if(curSum >= 0) curSum += curRemain;
else curSum = curRemain, pos = i;
total += curRemain;
}
return total >= 0 ? pos: -1;
}
};[LeetCode]Gas Station
最新推荐文章于 2024-10-12 23:30:39 发布
本文介绍了一种使用C++实现的解决方案,用于解决环形加油站问题。该问题要求找到一个起始加油站,从该站出发,车辆可以绕环形路一圈并返回到起点而不会中途耗尽燃料。通过遍历每个加油站并跟踪剩余燃料,可以有效地找到解决方案。
174

被折叠的 条评论
为什么被折叠?



