【Gas Station】cpp

题目

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.

代码

复制代码
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
            if ( gas.size() != cost.size() ) return -1; 
            int start_station = -1;
            int tmp_sum = 0;
            int total = 0;
            for (size_t i = 0; i < gas.size(); ++i)
            {
                tmp_sum += gas[i] - cost[i];
                total += gas[i] - cost[i];
                if (tmp_sum<0)
                {
                    tmp_sum=0;
                    start_station = i;
                }
            }
            return total>=0 ? start_station+1 : -1;  
    }
};
复制代码

Tips:

1. 采用贪心算法的思想:维护一个tmp_sum,计算从开始节点到当前节点损耗之差;如果小于零,则直接放弃;否则,继续累加。

2. 最终判断能不能完成行程,需要维护一个total:如果total大于等于0,则判定一定可以走完这趟旅程。这是为什么呢?具体原理可以参见鸽巢原理。

参考资料
贪心算法http://zh.wikipedia.org/wiki/贪心法

鸽巢原理http://zh.wikipedia.org/wiki/鴿巢原理

===========================================================

第二次过这道题,一次AC了,大体思路记得比较清楚。写法完全按照自己理解了,与原来的代码已经不太一样了。

复制代码
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
            const int gas_n = gas.size();
            const int cost_n = cost.size();
            if ( gas_n!= cost_n ) return -1;
            int total_compare = 0;
            int curr_gas = 0;
            int start = 0;
            for ( int i=0; i<cost_n; ++i )
            {
                if ( curr_gas==0 ) start = i;
                curr_gas = curr_gas + gas[i] - cost[i];
                if ( curr_gas<0 ) curr_gas = 0;
                total_compare = total_compare + gas[i] - cost[i];
            }
            return total_compare>=0 ? start : -1;
    }
};
复制代码

 

posted on   承续缘  阅读(209)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示