LintCode Gas Station加油站

本文探讨了一个有趣的问题:在一条环路上有N个加油站,每个加油站都有一定的汽油量和从一个加油站到下一个加油站所需的汽油量。文章提供了一种算法来确定是否能够从某个加油站出发并完成环路,并给出出发加油站的编号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一条环路上有 N 个加油站,其中第 i 个加油站有汽油gas[i],并且从第i个加油站前往第i+1个加油站需要消耗汽油cost[i]。

你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。

求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。

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

You have a car with an unlimited gas tank and it costs cost[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.

样例
现在有4个加油站,汽油量gas[i]=[1, 1, 3, 1],环路旅行时消耗的汽油量cost[i]=[2, 2, 1, 1]。则出发的加油站的编号为2。

Example
Given 4 gas stations with gas[i]=[1,1,3,1], and the cost[i]=[2,2,1,1]. The starting gas station’s index is 2.

注意
数据保证答案唯一。

挑战
O(n)时间和O(1)额外空间

Note
The solution is guaranteed to be unique.

Challenge
O(n) time and O(1) extra space

O(n) time and O(1) extra space
public class Solution {
    /**
     * @param gas: an array of integers
     * @param cost: an array of integers
     * @return: an integer
     */
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if (gas.length != cost.length) return -1;
        int index = 0;
        int sumgas = 0;
        for(int i = 0; i < gas.length; i++) {
            sumgas += gas[i] - cost[i];
            if (gas[i] - cost[i] < 0 && sumgas < 0) index = i + 1;
        }
        if(sumgas < 0) return -1;
        return index >= gas.length ? -1 : index;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值