【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; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?