Skip to content

Commit

Permalink
添加 0134. 加油站.md C语言贪心解法方法二
Browse files Browse the repository at this point in the history
  • Loading branch information
KingArthur0205 committed Apr 21, 2022
1 parent 4f4a54f commit 4154d3d
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions problems/0134.加油站.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ var canCompleteCircuit = function(gas, cost) {
```

### C
贪心算法:方法一
```c
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
int curSum = 0;
Expand Down Expand Up @@ -370,5 +371,36 @@ int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
}
```
贪心算法:方法二
```c
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
int curSum = 0;
int totalSum = 0;
int start = 0;
int i;
for(i = 0; i < gasSize; ++i) {
// 当前i站中加油量与耗油量的差
int diff = gas[i] - cost[i];
curSum += diff;
totalSum += diff;
// 若0到i的加油量都为负,则开始位置应为i+1
if(curSum < 0) {
curSum = 0;
// 当i + 1 == gasSize时,totalSum < 0(此时i为gasSize - 1),油车不可能返回原点
start = i + 1;
}
}
// 若总和小于0,加油车无论如何都无法返回原点。返回-1
if(totalSum < 0)
return -1;
return start;
}
```

-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit 4154d3d

Please sign in to comment.