From 648b0d2edc8cbf6c46b673f54ef610ba0524d5e3 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 1 Jun 2023 01:03:49 -0500 Subject: [PATCH] =?UTF-8?q?Update=200134.=E5=8A=A0=E6=B2=B9=E7=AB=99.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0134.加油站.md | 90 +++++++++++++++++++++++++------------- 1 file changed, 60 insertions(+), 30 deletions(-) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index f432bf0b..ad9acfbc 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -249,44 +249,74 @@ class Solution { ``` ### Python +暴力法 ```python -# 解法1 -class Solution: - def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: - n = len(gas) - cur_sum = 0 - min_sum = float('inf') - - for i in range(n): - cur_sum += gas[i] - cost[i] - min_sum = min(min_sum, cur_sum) - - if cur_sum < 0: return -1 - if min_sum >= 0: return 0 - - for j in range(n - 1, 0, -1): - min_sum += gas[j] - cost[j] - if min_sum >= 0: - return j - - return -1 -``` -```python -# 解法2 class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: - start = 0 - curSum = 0 - totalSum = 0 + for i in range(len(cost)): + rest = gas[i] - cost[i] # 记录剩余油量 + index = (i + 1) % len(cost) # 下一个加油站的索引 + + while rest > 0 and index != i: # 模拟以i为起点行驶一圈(如果有rest==0,那么答案就不唯一了) + rest += gas[index] - cost[index] # 更新剩余油量 + index = (index + 1) % len(cost) # 更新下一个加油站的索引 + + if rest >= 0 and index == i: # 如果以i为起点跑一圈,剩余油量>=0,并且回到起始位置 + return i # 返回起始位置i + + return -1 # 所有起始位置都无法环绕一圈,返回-1 + +``` +贪心(版本一) +```python +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + curSum = 0 # 当前累计的剩余油量 + minFuel = float('inf') # 从起点出发,油箱里的油量最小值 + + for i in range(len(gas)): + rest = gas[i] - cost[i] + curSum += rest + if curSum < minFuel: + minFuel = curSum + + if curSum < 0: + return -1 # 情况1:整个行程的总消耗大于总供给,无法完成一圈 + + if minFuel >= 0: + return 0 # 情况2:从起点出发到任何一个加油站时油箱的剩余油量都不会小于0,可以从起点出发完成一圈 + + for i in range(len(gas) - 1, -1, -1): + rest = gas[i] - cost[i] + minFuel += rest + if minFuel >= 0: + return i # 情况3:找到一个位置使得从该位置出发油箱的剩余油量不会小于0,返回该位置的索引 + + return -1 # 无法完成一圈 + +``` +贪心(版本二) +```python +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + curSum = 0 # 当前累计的剩余油量 + totalSum = 0 # 总剩余油量 + start = 0 # 起始位置 + for i in range(len(gas)): curSum += gas[i] - cost[i] totalSum += gas[i] - cost[i] - if curSum < 0: - curSum = 0 - start = i + 1 - if totalSum < 0: return -1 + + if curSum < 0: # 当前累计剩余油量curSum小于0 + start = i + 1 # 起始位置更新为i+1 + curSum = 0 # curSum重新从0开始累计 + + if totalSum < 0: + return -1 # 总剩余油量totalSum小于0,说明无法环绕一圈 return start + + ``` ### Go