#leetcode#Gas Station

来源:互联网 发布:三菱plc编程图形图 编辑:程序博客网 时间:2024/05/02 03:01

这位博主分析的太透彻,

原帖:

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


贴一段Java 的代码

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

// http://blog.csdn.net/kenden23/article/details/14106137public 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;            }}


0 0