[leetcode]134. Gas Station

题目链接:https://leetcode.com/problems/gas-station/#/description

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

You have a car with an unlimited gas tank and it costs cost[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.


思路:

我们首先从i站点出发,若走到当前站点cur我们的油量<0,那么只需要从cur+1继续出发试探即可。在此不进行证明,但是我们可以宏观的想一下,前面的任意的前缀站点段的油量和肯定是>0的,那么去掉任意一个前缀,只会使油量变得更少,所以我们只能尝试从cur+1重新开始。


class Solution {
public:
    int canCompleteCircuit(vector &gas, vector &cost)
    {
        if (gas.size() == 0 || cost.size() == 0 || gas.size() != cost.size()) return -1;
        int total = 0, sum = 0, start = 0;
        for (int i = 0; i < gas.size(); ++i)
        {
            total += (gas[i] - cost[i]);
            if (sum < 0)
            { //发现油箱空了,从下一个站点尝试
                sum = (gas[i] - cost[i]);
                start = i;
            }
            else
                sum += (gas[i] - cost[i]);
        }
        return total < 0 ? -1 : start; //用total判断start 是否是满足要求的解
    }
};


你可能感兴趣的:(leetcode,贪心)