mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 0134. 加油站.md C语言贪心解法方法二
This commit is contained in:
@ -341,6 +341,7 @@ var canCompleteCircuit = function(gas, cost) {
|
||||
```
|
||||
|
||||
### C
|
||||
贪心算法:方法一
|
||||
```c
|
||||
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
|
||||
int curSum = 0;
|
||||
@ -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>
|
||||
|
Reference in New Issue
Block a user