leetcode---gas-station---贪心

本文探讨了一种特定的算法问题:给定环路上的加油站及其油量与从一站到下一站所需的油耗,如何找到能够完成环路旅程的起始加油站。通过分析加油站数量、油量与消耗之间的关系,提出了一种有效解决方案。

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

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.

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) 
    {
        int n = gas.size();
        if(n == 0)
            return 0;

        int gasSum = 0, costSum = 0;
        for(int i=0; i<n; i++)
        {
            gasSum += gas[i];
            costSum += cost[i];
        }
        if(gasSum < costSum)
            return -1;

        int maxDis = -1, id = 0;
        for(int i=0; i<n; i++)
        {
            int tmp = 0;
            tmp += gas[i] - cost[i];
            if(tmp < 0)
                continue;
            for(int j=i+1; j!=i; (++j)%=n)
            {
                tmp += gas[j%n] - cost[j%n];
                if(tmp < 0)
                    break;
            }
            if(tmp > maxDis)
            {
                maxDis = tmp;
                id = i;
            }
        }
        return id;
    }
};
### LeetCode 加油站问题 C++ 实现解释与优化 #### 问题背景 加油站问题是经典的贪心算法应用之一。其核心目标是从一系列加油站中找出一个可以作为起点的位置,使得车辆能够沿着环形路径完成一圈行驶而不会中途耗尽燃料。如果无法找到这样的位置,则返回 `-1` 表示无解。 --- #### 算法逻辑分析 此问题的核心思想基于两个条件判断: 1. 如果总加油量减去总消耗量的结果为负数,则无论从哪个站点出发都不可能完成整个循环。 2. 若总加油量大于等于总消耗量,则必然存在至少一个起始点满足条件。通过遍历数组记录当前剩余油量的变化趋势即可定位到合适的起始点[^3]。 具体实现上采用单次扫描的方式,在过程中维护三个变量: - `total_tank`: 记录全局累计的净增油量; - `current_tank`: 跟踪当前位置之前的累积净增油量; - `starting_station`: 当前假设的最优出发点索引。 当某一站点处发现 `current_tank < 0` 的情况时,说明之前选定的任何一点都不能成为有效起点,因此需重置 `current_tank=0` 并更新新的潜在起点至下一站。 --- #### C++ 实现代码 下面是完整的 C++ 实现版本: ```cpp #include <vector> using namespace std; class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int total_tank = 0; // 总油箱状态 int current_tank = 0; // 当前局部油箱状态 int starting_station = 0; // 候选起点 for (int i = 0; i < gas.size(); ++i) { total_tank += gas[i] - cost[i]; current_tank += gas[i] - cost[i]; if (current_tank < 0) { // 遇到不可达的情况 starting_station = i + 1; current_tank = 0; } } return total_tank >= 0 ? starting_station : -1; } }; ``` 上述代码实现了 O(n) 时间复杂度和 O(1) 空间复杂度的要求,其中 n 是输入数组长度。 --- #### 关键点解析 1. **为什么可以通过一次遍历来解决问题?** 这是因为一旦某个节点之后的所有子序列都保持非负差值(即加油量不低于花费),则这些部分都可以被安全跳过而不影响最终结果判定。 2. **如何处理边界条件?** 边界条件主要体现在两方面:一是所有站点均不构成闭环;二是某些特殊情况下只有一个或少数几个站点参与计算。程序设计已充分考虑这两种极端情形下的行为表现。 3. **时间与空间效率考量:** 整体流程仅涉及单一线性迭代操作,无需额外存储结构支持辅助运算,故具备较高执行效能。 --- #### 可能存在的改进方向 尽管现有方案已经非常高效,但仍可以从以下几个角度进一步探索可能性: - 对于大规模数据集引入并行化机制加速处理速度; - 结合动态规划方法提供更灵活多样的求解策略以应对不同变种需求。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值