134. 加油站

方法一
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int minSpare = std::numeric_limits<int>::max();
int spare = 0;
int len = gas.size();
int index = 0;
for (int i = 0; i < len; i++) {
spare += gas[i] - cost[i];
if (spare < minSpare) {
minSpare = spare;
index = i;
}
}
if (spare < 0) return -1;
if (minSpare >= 0) return 0;
return (index + 1) % len;
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
方法二
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int length = gas.size(), start = 0;
while(start < length){
int curSum = 0, count = 0;
while(count < length){
curSum = curSum + gas[(start+count)%length] - cost[(start+count)%length];
if(curSum < 0){
break;
}
count++;
}
if(count == length){
return start;
}
else{
start = start + count + 1;
}
}
return -1;
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23