LeetCode-Gas Station

细节需要注意 当数组wrap过来 那个position需要减n 但是那个计数的 i不可以减n 否则就会死循环

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        for ( int start = 0; start < n; start ++ ){
            int tank = 0;
            int i = start;
            for (; i < start + n; i ++ ){
                int pos = i;
                if ( i >= n )
                    pos -= n;
                tank += gas[pos] - cost[pos];
                if ( tank < 0 )
                    break;
            }
            if ( i == start + n )
                return start;
        }
        return -1;
    }
}


你可能感兴趣的:(LeetCode-Gas Station)