## [Positions] two pointers becomes gas station

### The general idea:

It is probably the meaning of the questions: a ring N sites, each site can refuel gas [i], each site to its site next to consume cost [i], ask if you can find a starting point to be able to walk all the ring point (end == starting point)

The idea is, in fact, can be understood reach each site to increase gas [i] -cost [i], of course, this number might be negative, but we must ensure that the total number of oil sum> = 0. Set a start pointer and a pointer to end and then if coupled sum> = 0, then the end ++, otherwise start - (total since start ++ will only make oil less, only fallback start see if you can get a positive number of gas [i] on a stand - cost [i] to increase total oil). Until start == sum, and then determines whether the final sum> = 0, i.e., whether or solution.

I feel I have learned is that this has a beginning and end uncertain start and end points have questions, you can set two pointers , different operations on different circumstances design pointer. (Feet before borrowing is this idea)

### AC Code:

``````class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start = gas.size()-1;
int end = 0;
int sum = gas[start] - cost[start];
while(start>end)
{
if(sum>=0)
{
sum += gas[end] - cost[end];
end++;
}
else
{
start--;
sum += gas[start] - cost[start];
}
}
if(sum>=0)
return start;
else
return -1;
}
};``````

### Guess you like

Origin blog.csdn.net/m0_38033475/article/details/92060134
Recommended
Ranking
Daily