#leetcode#Gas Station

这位博主分析的太透彻,

原帖:

http://blog.csdn.net/kenden23/article/details/14106137


贴一段Java 的代码

注意巧妙利用题目给的条件 —— gurantee unique solution

// http://blog.csdn.net/kenden23/article/details/14106137
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if(gas == null || gas.length == 0 || cost == null || cost.length == 0){
            return -1;
        }
        int total = 0;
        for(int i = 0; i < cost.length; i++){
            total += gas[i] - cost[i];
        }
        if(total < 0){
            return -1;
        }
        int j = -1;
        int sum = 0;
        for(int i = 0; i < cost.length; i++){
            sum += gas[i] - cost[i];
            if(sum < 0){
                j = i;
                sum = 0;
            }
        }
        return j + 1;
        
    }
}


你可能感兴趣的:(LeetCode)