[LeetCode] Gas Station 加油站问题

简介:

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.

Note:
The solution is guaranteed to be unique.

这道转圈加油问题不算很难,只要想通其中的原理就很简单。我们首先要知道能走完整个环的前提是gas的总量要大于cost的总量,这样才会有起点的存在。假设开始设置起点start = 0, 并从这里出发,如果当前的gas值大于cost值,就可以继续前进,此时到下一个站点,剩余的gas加上当前的gas再减去cost,看是否大于0,若大于0,则继续前进。当到达某一站点时,若这个值小于0了,则说明从起点到这个点中间的任何一个点都不能作为起点,则把起点设为下一个点,继续遍历。当遍历完整个环时,当前保存的起点即为所求。代码如下:

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int total = 0, sum = 0, start = 0;
        for (int i = 0; i < gas.size(); ++i) {
            total += gas[i] - cost[i];
            sum += gas[i] - cost[i];
            if (sum < 0) {
                start = i + 1;
                sum = 0;
            }
        }
        if (total < 0) return -1;
        else return start;
    }
};

本文转自博客园Grandyang的博客,原文链接:加油站问题[LeetCode] Gas Station ,如需转载请自行联系原博主。

相关文章
|
4月前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 134. 加油站 算法解析
☆打卡算法☆LeetCode 134. 加油站 算法解析
|
5月前
|
算法 网络架构
代码随想录算法训练营第三十三天 | LeetCode 1005. K 次取反后最大化的数组和、134. 加油站、135. 分发糖果
代码随想录算法训练营第三十三天 | LeetCode 1005. K 次取反后最大化的数组和、134. 加油站、135. 分发糖果
31 0
|
6月前
|
算法
代码随想录Day28 贪心03 LeetCode T1005 K次取反后最大化的数组和 LeetCode T134 加油站 LeetCode T135 分发糖果
代码随想录Day28 贪心03 LeetCode T1005 K次取反后最大化的数组和 LeetCode T134 加油站 LeetCode T135 分发糖果
20 0
|
12月前
|
索引
leetcode每日一题:134. 加油站
leetcode每日一题:134. 加油站
|
算法
leetcode 134 加油站
leetcode 134 加油站
40 0
leetcode 134 加油站
|
算法 Java C++
代码随想录刷题|LeetCode 1005.K次取反后最大化的数组和 134. 加油站 135. 分发糖果
代码随想录刷题|LeetCode 1005.K次取反后最大化的数组和 134. 加油站 135. 分发糖果
|
算法
LeetCode只加油站问题
分享算法题解,不走弯路进大厂
108 0
[LeetCode] Gas Station
To solve this problem, some observations have to be made first. Let's first see two relatively easy observations.
867 0
|
22天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2