LeetCode: Gas Station
来源:互联网 发布:跳跃网络次元大作战 编辑:程序博客网 时间:2024/06/08 00:39
思路:弄清两个点就可以了:
1. 如果所有加油站的存储油量和 大于 消耗油量和,则必定可以找到一个起始站走遍一圈(可以用书数学归纳法证明),否则,没有这样的一个起始站;
2. 在选了一个出发站begin 后,在绕圈的过程中,在第 i 个加油站,如果出现存储油量和 小于 消耗的油量和,则出发站必然不会在 begin 和 i之间,因为只有唯一一个出发站满足绕圈的条件。
所以,代码很显然了
code:
class Solution {public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int totalSum = 0, curSum = 0,begin = 0; int n = gas.size(); for(int i = 0;i < n;i++){ totalSum += (gas[i] - cost[i]); curSum += (gas[i] - cost[i]); if(curSum < 0){ begin = (i+1) % n; curSum = 0; } } if(totalSum < 0) return -1; return begin; }};
0 0
- 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
- [LeetCode]134.Gas Station
- [Leetcode] Gas Station (Java)
- gas station leetcode
- visio的一些用法
- db file parallel write和db file parallel read
- 回顾往昔,瞻望未来
- BZOJ 1025: [SCOI2009]游戏
- v4l2属性设置
- LeetCode: Gas Station
- 二进制补码
- UVA 10319 - Manhattan(2-SET)
- Android RGB颜色对照表
- 苹果Swift语言入门教程(摘自百度经验)
- UIButton通过UIEdgeInsetsMake设置image和title的位置
- Android 应用程序发布流程---碗豆荚发布流程
- myeclipse 项目报错
- 如何在同一台电脑使用不同的账号提交到同一个github仓库