Gas Station
2015-07-21 15:27
393 查看
描述
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.
【题意】
在环形路线上一共有N个加油站,每个加油站的存储容量为gas[i].你有一辆汽油无限存储的汽车,如果你从加油站i到下一站(i+1),你需要
消耗汽油cost[i] 你从某一个加油站开始你的旅程,但是你的汽车里没有任何的汽油。
如果你能沿着环形路线旅游一遍,返回你开始旅游的加油站的下标否则返回-1
分析:
如果最后剩油量大于0,则说明肯定有一条路线。
对于一个循环数组,如果这个数组整体和 SUM >= 0,那么必然可以在数组中找到这么一个元素:从这个数组元素出发,绕数组一圈,能保证累加和一直是出于非负状态。
如果这个前面的数累加和小余0,则后面的累加一定大于0.
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.
【题意】
在环形路线上一共有N个加油站,每个加油站的存储容量为gas[i].你有一辆汽油无限存储的汽车,如果你从加油站i到下一站(i+1),你需要
消耗汽油cost[i] 你从某一个加油站开始你的旅程,但是你的汽车里没有任何的汽油。
如果你能沿着环形路线旅游一遍,返回你开始旅游的加油站的下标否则返回-1
分析:
如果最后剩油量大于0,则说明肯定有一条路线。
对于一个循环数组,如果这个数组整体和 SUM >= 0,那么必然可以在数组中找到这么一个元素:从这个数组元素出发,绕数组一圈,能保证累加和一直是出于非负状态。
如果这个前面的数累加和小余0,则后面的累加一定大于0.
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int total = 0; int j = -1; for (int i = 0, sum = 0; i < gas.size(); ++i) { sum += gas[i] - cost[i]; total += gas[i] - cost[i]; if (sum < 0) { j = i; sum = 0; } } return total >= 0 ? j + 1 : -1; } };
相关文章推荐
- 如何使用VS2010调用visa进行程控
- 101-102=1
- C++将CBitmap类中的图像保存到文件的方法
- Android 四大组件学习之Service二
- 解决打包安装中出现 【无法在磁盘上找到项“Microsoft.Net.Framework.3.5.SP1”中的 xxxxx 】
- mysql c语言操作
- 【玩转cocos2d-x之二十四】截图保存功能的实现
- 【玩转cocos2d-x之二十三】多线程和同步03-图片异步加载
- 关于数理统计基础知识的一点补漏
- kvm 设置vnc远程登录
- 三目运算符
- freemarker页面如何获取绝对路径basePath
- NYOJ 298 相变点(矩阵高速功率)
- Zookeeper在hbase集群的作用
- hdu1114 — Piggy-Bank (完全背包)
- 杭电 2026 首字母变大写
- 【玩转cocos2d-x之二十二】多线程和同步02-售票
- System.ComponentModel.DataAnnotations.Schema 冲突
- 模拟iOS网络环境
- H264视频的sps和pps解析和哥伦布编码