Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4723ecc

Browse files
Merge pull request youngyangyang04#1216 from xiaofei-2020/greed11
添加(0134.加油站.md):增加typescript版本
2 parents fc121c6 + 82df90f commit 4723ecc

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

‎problems/0134.加油站.md‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ class Solution {
235235
return index;
236236
}
237237
}
238-
```
238+
```
239239

240240
### Python
241241
```python
@@ -364,7 +364,50 @@ var canCompleteCircuit = function(gas, cost) {
364364
};
365365
```
366366

367+
### TypeScript
368+
369+
**暴力法:**
370+
371+
```typescript
372+
function canCompleteCircuit(gas: number[], cost: number[]): number {
373+
for (let i = 0, length = gas.length; i < length; i++) {
374+
let curSum: number = 0;
375+
let index: number = i;
376+
while (curSum >= 0 && index < i + length) {
377+
let tempIndex: number = index % length;
378+
curSum += gas[tempIndex] - cost[tempIndex];
379+
index++;
380+
}
381+
if (index === i + length && curSum >= 0) return i;
382+
}
383+
return -1;
384+
};
385+
```
386+
387+
**解法二:**
388+
389+
```typescript
390+
function canCompleteCircuit(gas: number[], cost: number[]): number {
391+
let total: number = 0;
392+
let curGas: number = 0;
393+
let tempDiff: number = 0;
394+
let resIndex: number = 0;
395+
for (let i = 0, length = gas.length; i < length; i++) {
396+
tempDiff = gas[i] - cost[i];
397+
total += tempDiff;
398+
curGas += tempDiff;
399+
if (curGas < 0) {
400+
resIndex = i + 1;
401+
curGas = 0;
402+
}
403+
}
404+
if (total < 0) return -1;
405+
return resIndex;
406+
};
407+
```
408+
367409
### C
410+
368411
```c
369412
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
370413
int curSum = 0;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /