code第一部分數組:第二十題:加油站

code第一部分數組:第二十題:加油站

 

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: e solution is guaranteed to be unique。數組

 

分析ui

O(N) 的解法是,設置兩個變量, sum 判斷當前的指針的有效性; total 則判斷整個數組是否有
解,有就返回經過 sum 獲得的下標,沒有則返回 -1。spa

對於一個循環數組,若是這個數組總體和 SUM >= 0,那麼必然能夠在數組中找到這麼一個元素:從這個數組元素出發,繞數組一圈,能保證累加和一直是出於非負狀態。指針

int gasstation(int gas[],int cost[],int n)
{
    int total=0;
    int j=-1;
    int sum;
    for (int i = 0,sum=0; i < n; ++i)
    {
        sum+=gas[i]-cost[i];
        total+=gas[i]-cost[i];
        if (sum<0)
        {
            j=i;
            sum=0;
        }
    }
    return total>=0?j+1:-1;
}
相關文章
相關標籤/搜索