Gas Station

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.

思路:gas和cost的差值。如果整个差值的和是负数,说明不存在这样一个点。如果为非负,存在这个起点。那起点在哪里呢。起点为第一个[i,n]的和值为非负的区间的起点。

 

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {

    int tot=0;
    int start=0;
    int sum=0;
    int len=gas.size();
    for(int i=0;i<len;i++)
    {
        if(start==len)return -1;
        int d=gas[i]-cost[i];
        tot+=d;
        sum+=d;
        if(sum<0)
        {
            start=i+1;
            sum=0;
        }
    }
    if(tot<0)return -1;
    else return start;
        
    }
};

 

posted @ 2014-07-06 04:51  Hicandyman  阅读(125)  评论(0)    收藏  举报