题解 | 加油站
加油站
https://www.nowcoder.com/practice/3b1abd8ba2e54452b6e18b31780b3635
class Solution { public: /** * * @param gas int整型vector * @param cost int整型vector * @return int整型 */ int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { // write code here for(int i=0;i<gas.size();i++) // 依次查找选中的出发站 { int currentGas=gas[i]-cost[i]; // 当前油量 if(currentGas<0) // 若油量不合规,跳过 { continue; } for(int j=(i+1)%gas.size();j!=i;j=(j+1)%gas.size()) { currentGas+=gas[j]-cost[j]; // 依次计算油量 if(currentGas<0) // 若油量不合规,跳过 { break;; } } if(currentGas<0) { continue; } else { // 油量合规返回下标 return i; } } return -1; } };