mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #1216 from xiaofei-2020/greed11
添加(0134.加油站.md):增加typescript版本
This commit is contained in:
@ -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;
|
||||
|
Reference in New Issue
Block a user