原题
https://leetcode.cn/problems/gas-station/description/
思路
贪心
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
ans = 0
cur_remain = 0
total_remain = 0
n = len(gas)
for i in range(n):
cur_remain += gas[i] - cost[i]
total_remain += gas[i] - cost[i]
if cur_remain < 0:
ans = i + 1
cur_remain = 0
if total_remain < 0:
return -1
return ans
Go代码
func canCompleteCircuit(gas []int, cost []int) int {
ans := 0
cur_remain := 0
total_remain := 0
for i := 0; i < len(gas); i++ {
cur_remain += gas[i] - cost[i]
total_remain += gas[i] - cost[i]
// 0-i之间无法绕环路行驶一周
if cur_remain < 0 {
ans = i + 1
cur_remain = 0
}
}
// 0-n之间无法绕环路行驶一周
if total_remain < 0 {
return -1
} else {
return ans
}
}
1000

被折叠的 条评论
为什么被折叠?



