diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index 1777faad..e96773ff 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -235,7 +235,7 @@ class Solution { return index; } } -``` +``` ### Python ```python @@ -364,7 +364,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;