LeetCode——134. 加油站

题目描述:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

参考代码:

    public static int canCompleteCircuit(int[] gas, int[] cost) {
    
    
        int len=gas.length;
        //每一个节点可以走到终点,就放入index否则放入-1;最后返回数组中最大的元素即是答案
        //也可以直接不用数组,return即可
        int f=-1;
        int[] res=new int[len];
        int count;
        for (int i = 0; i < gas.length; i++) {
    
    
            count=gas[i]-cost[i];
            //如果当前选的不满足第一次直接赋值-1
            if(count<0)
            {
    
    
                res[i]=-1;
                continue;
            }
            //从i+1开始循环,结束的条件是返回原点,所以要加个数组长度再取余
            for (int j = i+1; f!=i; j++) {
    
    
                f=(j+len)%len;
                count+=gas[f];//加油
                count-=cost[f];//消耗的油
                if(count<0)//每一次都进行判断
                {
    
    
                    res[i]=-1;
                    break;
                }
            }//当遍历完也就是回到了原点,此时count>=0说明可以,直接赋值并退出第一层for循环
            if(count>=0)
            {
    
    
                res[i]=i;
                break;
            }
        }
        Arrays.sort(res);
        return res[res.length-1];
    }

感受下大佬的思路:

    public static int canCompleteCircuit2(int[] gas, int[] cost) {
    
    
        int rest = 0, run = 0, start = 0;
        for (int i = 0; i < gas.length; ++i){
    
    
            run += (gas[i] - cost[i]);
            rest += (gas[i] - cost[i]);
            if (run < 0){
    
    
                start = i + 1;
                run = 0;
            }
        }
        return rest < 0 ? -1: start;
    }

猜你喜欢

转载自blog.csdn.net/qq_44900959/article/details/109784282