Leetcode 134. Gas Station

2017-12-19  本文已影响0人  persistent100

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之和,那么肯定没有解决方案。
从头依次加gas-cost,如果小于0,那么以下一个为开始index。

int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) {
    int temp1=0,temp2=0,index=0;
    for(int i=0;i<gasSize;i++)
    {
        temp1+=gas[i]-cost[i];
        temp2+=gas[i]-cost[i];
        if(temp2<0)
        {
            temp2=0;
            index=i;
        }
    }
    if(temp1>=0)
    {
        if(index==0&&gas[0]>=cost[0])return 0;
        else return (index+1)%gasSize;
    }
    return -1;
}
上一篇下一篇

猜你喜欢

热点阅读