leetcode gas station 问题

leetcode 问题:

There are N gas stations along a circular route, where the amount of gas at station i isgas[i].

You have a car with an unlimited gas tank and it costscost[i]of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1


解答:

        想象一个环形的排满站点的路,长度为L,站点分别为:0,1...L-1。将整个路分为已经走过的白色部分和已经走过的红色的部分,红色和白色的端点分别用起点start和终点end来表示,红色的环必须满足一项条件:和为非负。起先我们可以假定一段已走过的路,假设起点在最后一个端点L-1,终点end在0处(这样会很方便处理)。那么用sum表示从L-1到0的和,如果sum大于等于0,那我们就可以向前延伸红色部分,也就是让end++,如果sum小于0那么我们只能通过向后延长红色部分试图使红色部分的和大于0,于是start--,这样的话无论sum是怎样的都会使end和start靠近,最终会有end==start。如果这个时候整个红色的部分是不小于0的,那么也就是能够保证有解而且解就是start==end的点,因为从这一点出发可以走到沿路都可以保证sum>=0。


c++代码:

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

        return -1;

猜你喜欢

转载自blog.csdn.net/wujianyongw4/article/details/80011781