LeetCode *** 134. Gas Station

来源:互联网 发布:园林景观设计软件下载 编辑:程序博客网 时间:2024/05/17 22:16

题目:

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

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from stationi 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.


分析:

。。我喜欢写代码。。。


代码:

class Solution {public:    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {        vector<int> rec=gas;        int size=gas.size(),total,ret=0;        bool flag;        for(int i=0;i<size;++i){            rec[i]-=cost[i];            rec.push_back(rec[i]);        }        while(ret<size){            if(rec[ret]>=0){                total=0;                flag=true;                for(int i=ret;i<ret+size;++i){                    total+=rec[i];                    if(total<0){                        ret=i+1;                        flag=false;                        break;                    }                }            }else ret++;            if(flag)break;        }        return ret<size?ret:-1;    }};

0 0
原创粉丝点击