134. 加油站 | LeetCode | Top Interview 150 | 编码题目
发布: (2025年12月18日 GMT+8 06:06)
1 min read
原文: Dev.to
Source: Dev.to
问题链接
https://leetcode.com/problems/gas-station/

解法
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalGas = 0;
int totalCost = 0;
for (int i = 0; i < gas.length; i++) {
totalGas += gas[i];
totalCost += cost[i];
}
if (totalGas < totalCost) {
return -1;
}
int currGas = 0;
int startIndex = 0;
for (int i = 0; i < gas.length; i++) {
currGas += gas[i] - cost[i];
if (currGas < 0) {
startIndex = i + 1;
currGas = 0;
}
}
return startIndex;
}
}