标签:
题目描述:public int CanCompleteCircuit(int[] gas, int[] cost) { var gasInCar = 0; var stopNo = 0; var i = 0; var counter = 0; while(stopNo < gas.Length){ if(gas[i] + gasInCar < cost[i]){ // failed , start at a new place and re count again gasInCar = 0; stopNo ++; i = NextStop(stopNo, gas.Length); counter = 0; } else{ gasInCar += gas[i]-cost[i]; i = NextStop(i, gas.Length); counter ++; } if(counter == gas.Length){ return i; } } return -1; } private int NextStop(int stop,int len){ if(stop < len - 1){ stop ++; } else { stop = 0; } return stop; }
public int CanCompleteCircuit(int[] gas, int[] cost) { var gasInCar = 0; var totalDelta = 0; var startAt = 0; for (var i = 0; i < gas.Length; i++) { var delta = gas[i] - cost[i]; if (gasInCar >= 0) { gasInCar += delta; } else { gasInCar = delta; startAt = i; } totalDelta += delta; } if (totalDelta >= 0){ return startAt; }else{ return -1; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/48897005