llllmz

导航

134. 加油站c

int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) {
    int sum=0,n=gasSize;
    for(int i=0;i<n;i++){
        gas[i]=gas[i]-cost[i];
        sum+=gas[i];
    }
    if(sum<0) return -1;
    int head=0,tail=0,count=0,x=0;
    while(count!=n){
        int t=x+gas[tail];
        if(t<0){
            if(head==tail){
                head=(head+1)%n;
                tail=(tail+1)%n;
            }else{
                x-=gas[head];
                head=(head+1)%n;
                count--;
            }
        }else{
            count++;
            x=t;
            tail=(tail+1)%n;
        }
    }
    return head;
}

 

posted on 2024-03-16 17:22  神奇的萝卜丝  阅读(15)  评论(0)    收藏  举报