From 82df90fd14fc8897559256a65d3ba53258daf262 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 7 Apr 2022 23:58:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880134.=E5=8A=A0?= =?UTF-8?q?=E6=B2=B9=E7=AB=99.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0134.加油站.md | 45 +++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index 1062a91c..d3b3d453 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -235,7 +235,7 @@ class Solution { return index; } } -``` +``` ### Python ```python @@ -340,7 +340,50 @@ var canCompleteCircuit = function(gas, cost) { }; ``` +### TypeScript + +**暴力法:** + +```typescript +function canCompleteCircuit(gas: number[], cost: number[]): number { + for (let i = 0, length = gas.length; i < length; i++) { + let curSum: number = 0; + let index: number = i; + while (curSum >= 0 && index < i + length) { + let tempIndex: number = index % length; + curSum += gas[tempIndex] - cost[tempIndex]; + index++; + } + if (index === i + length && curSum >= 0) return i; + } + return -1; +}; +``` + +**解法二:** + +```typescript +function canCompleteCircuit(gas: number[], cost: number[]): number { + let total: number = 0; + let curGas: number = 0; + let tempDiff: number = 0; + let resIndex: number = 0; + for (let i = 0, length = gas.length; i < length; i++) { + tempDiff = gas[i] - cost[i]; + total += tempDiff; + curGas += tempDiff; + if (curGas < 0) { + resIndex = i + 1; + curGas = 0; + } + } + if (total < 0) return -1; + return resIndex; +}; +``` + ### C + ```c int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){ int curSum = 0;