From e0237b5b4f151e84762d66280f464effe48f440d Mon Sep 17 00:00:00 2001 From: markwang Date: Wed, 31 Jul 2024 14:39:37 +0800 Subject: [PATCH] =?UTF-8?q?134.=E5=8A=A0=E6=B2=B9=E7=AB=99=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0Go=E8=B4=AA=E5=BF=83=E7=AE=97=E6=B3=95=EF=BC=88?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E4=B8=80=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0134.加油站.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index 1329bd9a..7ac9f0f9 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -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