Skip to content

Commit d344746

Browse files
authored
feat: update solutions to lc problem: No.0134
1 parent bbf6fec commit d344746

File tree

3 files changed

+48
-39
lines changed

3 files changed

+48
-39
lines changed

solution/0100-0199/0134.Gas Station/README.md

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -151,23 +151,26 @@ public:
151151
152152
```go
153153
func canCompleteCircuit(gas []int, cost []int) int {
154-
n := len(gas)
155-
i, j := n-1, n-1
156-
cnt, s := 0, 0
157-
for cnt < n {
158-
s += gas[j] - cost[j]
159-
cnt++
160-
j = (j + 1) % n
161-
for s < 0 && cnt < n {
162-
i--
163-
s += gas[i] - cost[i]
164-
cnt++
154+
totalGas, totalCost := 0, 0
155+
tank := 0
156+
startStation := 0
157+
158+
for i := 0; i < len(gas); i++ {
159+
totalGas += gas[i]
160+
totalCost += cost[i]
161+
tank += gas[i] - cost[i]
162+
163+
if tank < 0 {
164+
165+
startStation = i + 1
166+
tank = 0
165167
}
166168
}
167-
if s < 0 {
169+
170+
if totalGas < totalCost {
168171
return -1
169172
}
170-
return i
173+
return startStation
171174
}
172175
```
173176

solution/0100-0199/0134.Gas Station/README_EN.md

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -142,23 +142,26 @@ public:
142142
143143
```go
144144
func canCompleteCircuit(gas []int, cost []int) int {
145-
n := len(gas)
146-
i, j := n-1, n-1
147-
cnt, s := 0, 0
148-
for cnt < n {
149-
s += gas[j] - cost[j]
150-
cnt++
151-
j = (j + 1) % n
152-
for s < 0 && cnt < n {
153-
i--
154-
s += gas[i] - cost[i]
155-
cnt++
145+
totalGas, totalCost := 0, 0
146+
tank := 0
147+
startStation := 0
148+
149+
for i := 0; i < len(gas); i++ {
150+
totalGas += gas[i]
151+
totalCost += cost[i]
152+
tank += gas[i] - cost[i]
153+
154+
if tank < 0 {
155+
156+
startStation = i + 1
157+
tank = 0
156158
}
157159
}
158-
if s < 0 {
160+
161+
if totalGas < totalCost {
159162
return -1
160163
}
161-
return i
164+
return startStation
162165
}
163166
```
164167

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
func canCompleteCircuit(gas []int, cost []int) int {
2-
n := len(gas)
3-
i, j := n-1, n-1
4-
cnt, s := 0, 0
5-
for cnt < n {
6-
s += gas[j] - cost[j]
7-
cnt++
8-
j = (j + 1) % n
9-
for s < 0 && cnt < n {
10-
i--
11-
s += gas[i] - cost[i]
12-
cnt++
2+
totalGas, totalCost := 0, 0
3+
tank := 0
4+
startStation := 0
5+
6+
for i := 0; i < len(gas); i++ {
7+
totalGas += gas[i]
8+
totalCost += cost[i]
9+
tank += gas[i] - cost[i]
10+
11+
if tank < 0 {
12+
13+
startStation = i + 1
14+
tank = 0
1315
}
1416
}
15-
if s < 0 {
17+
18+
if totalGas < totalCost {
1619
return -1
1720
}
18-
return i
21+
return startStation
1922
}

0 commit comments

Comments
 (0)