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
}
复制代码