Skip to content

Commit 4e57c5f

Browse files
committed
ok
1 parent 21a62da commit 4e57c5f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/com/leetcode/Main134.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.leetcode;
2+
3+
/**
4+
* 134. 加油站
5+
* 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
6+
*
7+
* 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
8+
*
9+
* 如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
10+
* 输入:
11+
* gas = [1,2,3,4,5]
12+
* cost = [3,4,5,1,2]
13+
*
14+
* 输出: 3
15+
*
16+
* 解释:
17+
* 从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
18+
* 开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
19+
* 开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
20+
* 开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
21+
* 开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
22+
* 开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
23+
* 因此,3 可为起始索引。
24+
**/
25+
public class Main134 {
26+
public int canCompleteCircuit(int[] gas, int[] cost) {
27+
if (gas.length == 0 || cost.length == 0)
28+
return -1;
29+
int n = gas.length;
30+
int curTank = 0;
31+
int totalTank = 0;
32+
int startStage = 0;
33+
for (int i = 0; i < n; i++) {
34+
curTank += gas[i] - cost[i];
35+
totalTank += gas[i] - cost[i];
36+
if (curTank < 0) {
37+
startStage = i + 1;
38+
curTank = 0;
39+
}
40+
}
41+
return totalTank >= 0 ? startStage : -1;
42+
}
43+
}

0 commit comments

Comments
 (0)