2014年2月12日星期三

LeetCoder - Gas Station

 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:
The solution is guaranteed to be unique.

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = -1;
        loop: for(int i=0;i<gas.length;i++) {
            int gasall = 0;
            for(int j=0;j<gas.length;j++) {
                int nid = (j+i)%gas.length;
                gasall += gas[nid];
                gasall -= cost[nid];
                if(gasall<0) {
                    i = j+i;
                    continue loop;
                }
            }
            start = i;
            break;
        }
        return start;
    }
}

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
         loop: for(int i=0;i<gas.length;i++) {
             int gasLeft = 0;
             for(int j=0;j<gas.length;j++) {
                 gasLeft += gas[(j+i)%gas.length];
                 gasLeft -= cost[(j+i)%gas.length];
                 if(gasLeft<0) {
                     i = i + j;
                     continue loop;
                 }
             }
             return i;
         }
         return -1;
    }
}


==========

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int len = gas.length;
        for (int i = 0; i < len; i++) {
            boolean suc = true;
            int left = 0;
            for (int j = 0; j < len; j++) {
                int id = (i + j) % len;
                left += gas[id];
                left -= cost[id];
                if (left < 0) {
                    suc = false;
                    i = i + j;
                    break;
                }
            }
            if (suc) {
                return i;
            }
        }
        return -1;
    }
}

没有评论:

发表评论