My Java solution. be free to comment.


  • 0
    X
    public int canCompleteCircuit(int[] gas, int[] cost) {
    	for (int i = 0; i < gas.length; i++) {
    		int count = countMove(i, 0, 0, gas, cost);
    		if (count == gas.length)
    			return i;
    		else
    			i = i + count;
    	}
    	return -1;
    }
    
    // Map<Integer, Integer> map=new HashMap<Integer, Integer>();
    private int countMove(int i, int count, int g, int[] gas, int[] cost) {
    	// System.out.println("count= "+count +" i= "+i);
    	if (count == gas.length)
    		return count;
    
    	g = g + gas[i] - cost[i];
    	if (g < 0)
    		return count;
    	else
    		return countMove((++i) % gas.length, ++count, g, gas, cost);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.