[leetcode]Gas Station - java

两种解法

1. 两层遍历,直观取得结果 --- 时间复杂度高 ,不过, 但如果要求返回所有满足的位置,可以用这种方法

2. 题目只要求返回一个结果即可,那么有以下两个条件,即满足题意

a. ∑gas[i] >= ∑cost[i] 

b. 从cost[i]-gas[i]的负数最小的地方,往后找到第一个cost[i]-gas[i]>0的index,则此位置即满足要求

 

第一种解法,(time limit exceeded)

 public int canCompleteCircuitFailed(int[] gas, int[] cost) {
        if(gas == null || gas.length==0){
            return -1;
        }
        for(int i=0; i<gas.length; i++){
            if(cost[i]>gas[i]){
                continue;
            }
            int totalGas =0 ;
            int totalCost =0 ;
            int j=i;
            boolean circuitFlag = true;
            while (true){
                if(j == i && circuitFlag){
                    circuitFlag = false;
                }else if(j==i && !circuitFlag ){
                    return i;
                }
                totalCost += cost[j];
                totalGas += gas[j];
                if(totalCost > totalGas){
                    break;
                }
                if((j+1)==gas.length){
                    j = 0;
                }else {
                    j++;
                }
            }
            continue;
        }
        return -1;
    }

 

第二种

 public int canCompleteCircuit(int[] gas, int[] cost) {
        int gasCostMin = 0;
        int gasMinIndex = -1;
        int totalGas = 0;
        int totalCost = 0;
        for(int i=0; i<gas.length; i++){
            if((gas[i]-cost[i]) < gasCostMin){
                gasCostMin = gas[i]-cost[i];
                gasMinIndex = i;
            }
            totalCost += cost[i];
            totalGas += gas[i];
        }
        if(totalGas >= totalCost){
            if(gasMinIndex == -1){
                return 0;
            }
            int j = gasMinIndex;
            while (true){
                if(gas[j]-cost[j]>0){
                    return j;
                }
                j++;
                if(j==gas.length){
                       j=0;
                }
            }
        }
        return -1;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值