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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值