class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int left_oil = 0;
int pos = 0;
int num = gas.size();
int iterations = num * 2;
int start = 0, end = 0;
for (int i = 0; i < num * 2; i ++){
left_oil += gas[i % num];
if (left_oil < cost[i % num]){
left_oil = 0;
start = (i + 1) % num;
end = (i + 1) % num;
}
else{
end ++;
left_oil -= cost[i % num];
if (end - start > num){
return start;
}
}
}
return -1;
}
};
本文深入探讨了使用C++解决加油站问题的算法实现,通过一个循环遍历的方法找到能够完成环形旅程的起点,该算法考虑了油量与消耗之间的平衡,确保车辆能够在不额外加油的情况下完成整个环路。
476

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



