134. Gas Station

来源:互联网 发布:有声自动阅读软件 编辑:程序博客网 时间:2024/06/08 01:29

Problem:

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.

Note:
The solution is guaranteed to be unique.


题意是有一段环形的路,路上有n个加油站,第i个加油站对应就有gas[i]那么多的汽油,然后你开着一个汽车,汽车的装油没有上限,而你从第i个加油站到i+1个加油站要用cost[i]那么多的汽油,然后你从0汽油开始出发,问从哪个加油站开始可以绕一圈这段路,如果不存在的话返回-1。


如果用O(n^2)的当然是一下子就想到,对每个点都进行一次循环判断。但是这样可能就会超时,有没有更好的方法呢?

其实假如从第一个站开始,经过前k个站,发现汽油不够了,这时候的话这几个站都可以不用考虑了,因为本来油就少了,去掉开头的站也是缺油的。所以这个时候就重新从第k+1个站开始考虑。然后还要用一个total值来保存整个旅程的汽油剩余量,假如小于0,表示是不存在的,可以返回-1。sum用来计算经过后的剩余量。


Code:(LeetCode运行6ms)

class Solution {public:    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {        int sum = 0, total = 0;        int result = -1;        for (int i = 0; i < gas.size(); i++) {            sum += gas[i] - cost[i];            total += gas[i] - cost[i];                        if (sum < 0) {                sum = 0;                result = i;            }        }        if (total >= 0) {            return result + 1;        } else {            return -1;        }    }};