[leetcode]134. Gas Station
来源:互联网 发布:逛淘宝费流量多少 编辑:程序博客网 时间:2024/06/01 18:24
题目链接:https://leetcode.com/problems/gas-station/#/description
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.
思路:
我们首先从i站点出发,若走到当前站点cur我们的油量<0,那么只需要从cur+1继续出发试探即可。在此不进行证明,但是我们可以宏观的想一下,前面的任意的前缀站点段的油量和肯定是>0的,那么去掉任意一个前缀,只会使油量变得更少,所以我们只能尝试从cur+1重新开始。
class Solution {public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { if (gas.size() == 0 || cost.size() == 0 || gas.size() != cost.size()) return -1; int total = 0, sum = 0, start = 0; for (int i = 0; i < gas.size(); ++i) { total += (gas[i] - cost[i]); if (sum < 0) { //发现油箱空了,从下一个站点尝试 sum = (gas[i] - cost[i]); start = i; } else sum += (gas[i] - cost[i]); } return total < 0 ? -1 : start; //用total判断start 是否是满足要求的解 }};
阅读全文
0 0
- [LeetCode]134.Gas Station
- LeetCode 134. Gas Station
- [Leetcode] 134. Gas Station
- [leetcode] 134. Gas Station
- Leetcode-134.Gas Station
- 134. Gas Station LeetCode
- Leetcode 134. Gas Station
- [LeetCode]134. Gas Station
- LeetCode 134. Gas Station
- leetcode 134. Gas Station
- LeetCode *** 134. Gas Station
- LeetCode 134. Gas Station
- 【LeetCode】134. Gas Station
- LeetCode - 134. Gas Station
- LeetCode 134. Gas Station
- LeetCode 134. Gas Station
- [leetcode] 134. Gas Station
- leetcode-134. Gas Station
- 刷机我的ipad
- 并发工具类:等待多线程完成的CountDownLatch,和join的区别
- 25.struts2_自定义验证器和编程验证
- html5+express实现拖拽上传
- 新闻客户端
- [leetcode]134. Gas Station
- 单例设计模式
- IOS Swift 3.0 NSData与String相互转化
- java IO 示例 ,体现适配器模式
- LeetCode第七题--反转32位的整数
- 2017面试经历
- 7层网络协议对应的例子
- vb.net 教程 3-7 窗体编程 菜单和工具栏 1 MenuStrip
- 图像二值化