【leetcode】Gas Station
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.
Hide Tags
Greedy注意一点,如果车从0,开到i没有油了,那么我们下一个尝试的点应该为i+1。
因为在0点加了油,开到1时必定有剩余,实际上对于后面的点来说,初始油量是多了的
所以如果从0开始都到不了i,说明0到i之间的任何点都到不了。
1 class Solution { 2 public: 3 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { 4 5 6 int total_oil=0; 7 int index=0; 8 int n=gas.size(); 9 10 11 12 for(int i=0;i<n;i++) 13 { 14 total_oil+=gas[i]; 15 total_oil-=cost[i]; 16 17 if(total_oil<0) 18 { 19 total_oil=0; 20 index=i+1; 21 } 22 } 23 24 //如果循环到了最后一个,没了油,说明任何点都没有希望到达了 25 if(index==n) 26 { 27 return -1; 28 } 29 30 //如果一直循环到最后,仍然有油,说明从0点可以遍历整个路径 31 if(index==0) 32 { 33 return 0; 34 } 35 36 //如果开到最后还剩油,我们继续往后计算。 37 for(int i=0;i<n;i++) 38 { 39 total_oil+=gas[i]; 40 total_oil-=cost[i]; 41 42 //又回到了初始点,则说明从该点可以遍历整个路径 43 if(i==index) 44 { 45 return i; 46 } 47 48 //如果在中间任何一点没有了油,就不必再尝试了 49 if(total_oil<0) 50 { 51 break; 52 } 53 } 54 55 56 return -1; 57 } 58 };
分类:
算法研究
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现