Leetcode134题 加油站

int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){

    int sum = 0, index = -1, total = 0;     //sum记录总补给和油耗,index记录节点,total记录暂时的补给和油耗
    for(int i = 0; i < gasSize; ++i){
        sum = sum + gas[i] - cost[i];
        total = total + gas[i] - cost[i];
        if(total < 0){  //如果total小于0,则表示如果没有空油箱的情况下不能跑完这段路程,则记录index = i
            index = i;
            total = 0;
        }
    }

    return sum<0 ? -1 : index+1; //index = -1,如果没有一段路程的total小于0,则从0节点开始跑(任意节点)

}

比官方的简洁,相当于记录亏油的路线,从他的下一个节点作为初始节点。

posted @ 2021-11-29 20:34  冬日寻雾记  阅读(30)  评论(0)    收藏  举报