mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #2660 from markwang1992/134-canCompleteCircuit
134.加油站增加Go贪心算法(方法一)
This commit is contained in:
@ -345,6 +345,37 @@ class Solution:
|
||||
```
|
||||
|
||||
### Go
|
||||
|
||||
贪心算法(方法一)
|
||||
```go
|
||||
func canCompleteCircuit(gas []int, cost []int) int {
|
||||
curSum := 0
|
||||
min := math.MaxInt64
|
||||
for i := 0; i < len(gas); i++ {
|
||||
rest := gas[i] - cost[i]
|
||||
curSum += rest
|
||||
if curSum < min {
|
||||
min = curSum
|
||||
}
|
||||
}
|
||||
if curSum < 0 {
|
||||
return -1
|
||||
}
|
||||
if min >= 0 {
|
||||
return 0
|
||||
}
|
||||
for i := len(gas) - 1; i > 0; i-- {
|
||||
rest := gas[i] - cost[i]
|
||||
min += rest
|
||||
if min >= 0 {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
```
|
||||
|
||||
贪心算法(方法二)
|
||||
```go
|
||||
func canCompleteCircuit(gas []int, cost []int) int {
|
||||
curSum := 0
|
||||
|
Reference in New Issue
Block a user