leetcode题目:gas-station 使用start/end方法的个人理解
来源:互联网 发布:win8开始菜单软件 编辑:程序博客网 时间:2024/06/13 05:11
题目: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.
最近在刷leetcode的题目,看到这道题我用贪心,常规方法循环解可以ac。看别人的想法,用start和end来思考,挺有意思的,感觉特别巧妙,怕自己忘,写在这里吧。
代码
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int n=gas.size(); int end=0; int start=n-1; int sum=gas[start]-cost[start]; while(start>end){ if(sum>0){ sum+=gas[end]-cost[end]; ++end; } else{ --start; sum+=gas[start]-cost[start]; } } return sum>=0?start:-1; }
接下来解释下这种方法为什么可行。假设有5个节点吧,gas分别是 a1~a5 ,cost分别是b1~b5 。 如图顺时针考虑。
外循环是start和end相等时结束,就是他俩相遇了。初始让start在a5 , end在a1。我只假设3中情况:1、在a5相遇。2、在a1相遇。3、在中间相遇。
1、a5相遇
在a5相遇是因为end顺时针走到a5,怎么走的呢?第一次sum=a5-b5,因为sum>=0,end才能往前走,说明从a5走到a1的油足够,下一次end再往前走,说明上一次省的油(sum中保存)加上a1-b1 的和还是>=0,这个车可以一直走下去。直到最后sum=(车走到a4处剩余的油)+(a4-b4),退出循环,只要判断这个sum是不是>=0,就知道车从a5出发能不能转一圈回来了。
2、在a1相遇
在a1相遇需要start不断减1减到a1处,为什么start要递减呢?因为判断了sum<0了,小于0说明第一次从a5出发到a1的油不够了,那车就从a4出发吧(start减1),看看从a4出发能不能剩油,同时剩的油能不能填补a5到a1那段不够的油,要是还不够,那start继续减1,看看从a3那出发行不行。结果呢,一直到a2都不够,那最后sum=(在a2出发不够的油)+(a1-b1),在end处重合,退出循环。然后判断一下sum够不够,够的话就从a1出发。
3、在中间相遇(假设就在a3相遇吧)
在a3相遇就是说end要顺时针走到a3,start要逆时针走到a3。end++的解释和start--的解释都在上面了。
最后加一句其实,总的油量只要大于等于总的花费量,就一定存在一个点让车能走一圈。每次退出循环的sum都等于总油量减去总花费。如果sum<0,那就不存在,否则,退出循环的那个点就是可以的出发点。当然可能出发点有多个,这种方法就看初始位置选在哪里了。
- leetcode题目:gas-station 使用start/end方法的个人理解
- LeetCode算法题目:Gas Station
- Gas Station [leetcode] 的两种解法
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- jQuery事件之表单事件
- servlet实现简单的聊天室
- 使用dm-cache,将SSD用作HDD的Cache
- 史上最简单的SpringCloud教程 | 第六篇: 分布式配置中心(Spring Cloud Config)
- 优化 | 重要的MySQL开发规范都在这了
- leetcode题目:gas-station 使用start/end方法的个人理解
- 【CF GYM101341I】Matrix God 题解
- 【模式串个数匹配】+ KMP
- NYOJ 1237 最大岛屿(DFS)
- 一个止步于64强的小白对于2017年华为挑战赛的总结(java+spfa+最小代价最大流+启发式算法)
- iframe访问父级页面、子级页面
- Scrapy在win7 32位的安装及依赖包
- FZU2087-统计树边
- Servlet学习日记一——一个简单的HelloWorldServlet程序