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.
贪心or动态规划?
从gas[0]开始走,遇到油不够的情况,开始station就后退一步,利用以前算的结果可以只算出第一步的油量。直到最后,算出circle的连接点是否满足。
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int n = gas.length; int start = 0, end = 0, have = 0, cur = 0; for(int i=0; i<n-1; i++) { have += gas[cur] - cost[cur]; if(have >= 0) { end ++; cur = end; } else { start --; if(start < 0) { start = n - 1; } cur = start; } } have += gas[cur] - cost[cur]; return have>=0?start:-1; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步