37 lines
920 B
Java
37 lines
920 B
Java
/*
|
||
* @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
|
||
|