Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e0237b5

Browse files
134.加油站增加Go贪心算法(方法一)
1 parent 6bb97b5 commit e0237b5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎problems/0134.加油站.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,37 @@ class Solution:
345345
```
346346

347347
### Go
348+
349+
贪心算法(方法一)
350+
```go
351+
func canCompleteCircuit(gas []int, cost []int) int {
352+
curSum := 0
353+
min := math.MaxInt64
354+
for i := 0; i < len(gas); i++ {
355+
rest := gas[i] - cost[i]
356+
curSum += rest
357+
if curSum < min {
358+
min = curSum
359+
}
360+
}
361+
if curSum < 0 {
362+
return -1
363+
}
364+
if min >= 0 {
365+
return 0
366+
}
367+
for i := len(gas) - 1; i > 0; i-- {
368+
rest := gas[i] - cost[i]
369+
min += rest
370+
if min >= 0 {
371+
return i
372+
}
373+
}
374+
return -1
375+
}
376+
```
377+
378+
贪心算法(方法二)
348379
```go
349380
func canCompleteCircuit(gas []int, cost []int) int {
350381
curSum := 0

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /