Files
leetcode/134.gas-station.java
2025-10-28 01:43:48 +08:00

37 lines
920 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* @lc app=leetcode id=134 lang=java
*
* [134] Gas Station
*/
// @lc code=start
class Solution {
/**
* 本题核心为若从i开始计算到j时发现不行那么从(i, j]范围内任一站点开始也不行,易进行论证
*
* @param gas
* @param cost
* @return
*/
public int canCompleteCircuit(int[] gas, int[] cost) {
int start = 0, sum = 0, curIdx = 0;
while(start < gas.length) {
if(curIdx - start == gas.length) {
return start;
}
int pos = curIdx % gas.length;
if(sum + gas[pos] - cost[pos] < 0) {
curIdx++;
start = curIdx;
sum = 0;
} else {
sum += gas[pos] - cost[pos];
curIdx++;
}
}
return -1;
}
}
// @lc code=end