mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 0134.加油站.md
0134.加油站的Java解法三
This commit is contained in:
@ -249,6 +249,29 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```
|
||||||
|
// 解法3
|
||||||
|
class Solution {
|
||||||
|
public int canCompleteCircuit(int[] gas, int[] cost) {
|
||||||
|
int tank = 0; // 当前油量
|
||||||
|
int totalGas = 0; // 总加油量
|
||||||
|
int totalCost = 0; // 总油耗
|
||||||
|
int start = 0; // 起点
|
||||||
|
for (int i = 0; i < gas.length; i++) {
|
||||||
|
totalGas += gas[i];
|
||||||
|
totalCost += cost[i];
|
||||||
|
|
||||||
|
tank += gas[i] - cost[i];
|
||||||
|
if (tank < 0) { // tank 变为负数 意味着 从0到i之间出发都不能顺利环路一周,因为在此i点必会没油
|
||||||
|
tank = 0; // reset tank,类似于题目53.最大子树和reset sum
|
||||||
|
start = i + 1; // 起点变为i点往后一位
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (totalCost > totalGas) return -1;
|
||||||
|
return start;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Python
|
### Python
|
||||||
暴力法
|
暴力法
|
||||||
|
Reference in New Issue
Block a user