添加(0134.加油站.md):增加typescript版本

This commit is contained in:
Steve2020
2022-04-07 23:58:15 +08:00
parent 5c3ab04b6e
commit 82df90fd14

View File

@ -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;