https://leetcode.cn/problems/gas-station/description/?envType=study-plan-v2&envId=top-interview-150
go
package leetcode150 import "testing" func TestCanCompleteCircuit(t *testing.T) { gas := []int{2} cost := []int{2} res := canCompleteCircuit(gas, cost) println(res) } func canCompleteCircuit(gas []int, cost []int) int { if len(gas) == 0 || len(cost) == 0 { return 0 } for i := range gas { cost[i] = gas[i] - cost[i] } var ff []int posMap := make(map[int]int) sPos := 0 total := 0 for i := range cost { if cost[i] > 0 && total < 0 { ff = append(ff, total) posMap[len(ff)-1] = sPos sPos = i total = cost[i] } else if cost[i] < 0 && total > 0 { ff = append(ff, total) posMap[len(ff)-1] = sPos sPos = i total = cost[i] } else if cost[i] > 0 && total >= 0 { total += cost[i] } else if cost[i] < 0 && total <= 0 { total += cost[i] } if i+1 == len(cost) && total != 0 { if len(ff) == 0 { ff = append(ff, total) posMap[0] = sPos } else if total > 0 && ff[0] > 0 { ff[0] += total posMap[0] = sPos } else if total < 0 && ff[0] < 0 { ff[0] += total posMap[0] = sPos } else { ff = append(ff, total) posMap[len(ff)-1] = sPos } } } total1 := 0 total2 := 0 for _, v := range ff { if v < 0 { total1 += v } else { total2 += v } } if total1+total2 < 0 { return -1 } if len(ff) == 0 { return 0 } for i, v := range ff { if v > 0 && v+ff[(i+1)%len(ff)] >= 0 { return posMap[i] } } return -1 }
官方题解
func canCompleteCircuit(gas []int, cost []int) int { for i, n := 0, len(gas); i < n; { sumOfGas, sumOfCost, cnt := 0, 0, 0 for cnt < n { j := (i + cnt) % n sumOfGas += gas[j] sumOfCost += cost[j] if sumOfCost > sumOfGas { break } cnt++ } if cnt == n { return i } else { i += cnt + 1 } } return -1 }
分类:
leetcode面试经典150题
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话