每日AC--gas-station--LeetCode

实战 Java 并发编程
实战为导向,从Java 并发原理出发,并集合开发实践,全面剖析 Java 并发编程。
wangxiaoming


每日AC--gas-station--LeetCode


题目描述


There are N gas stations along a circular route, where the amount of gas at station i isgas[i].

You have a car with an unlimited gas tank and it costscost[i]of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note: 
 The solution is guaranteed to be unique.



AC代码

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int len = gas.length;
        for(int i = 0; i < len; i++){
            if(canComplete(i,gas,cost)){
                return i;
            }
        }
        return -1;
    }
     
    public boolean canComplete(int start, int[] gas, int[] cost){
        int len = gas.length;
        int total = 0;
        for (int i = start; i < len + start; i++) {
            if (total + gas[i % len] < cost[i%len]) {
                return false;
            } else {
                total = total + gas[i % len] - cost[i%len];
            }
        }
        return true;
    }
}


wangxiaoming CSDN认证博客专家 架构 Spring Boot Redis
博客是很好的总结和记录工具,如果有问题,来不及回复,关注微信公众号:程序员开发者社区,获取我的联系方式,向我提问,也可以给我发送邮件,联系 1275801617@qq.com
©️2020 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值