美文网首页
Leetcode 134. Gas Station

Leetcode 134. Gas Station

作者: persistent100 | 来源:发表于2017-12-19 16:04 被阅读0次

    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;
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 134. Gas Station

          本文链接:https://www.haomeiwen.com/subject/wcfiwxtx.html