134. Gas Station Add to List
来源:互联网 发布:美工提升 编辑:程序博客网 时间:2024/06/10 18:36
There are N gas stations along a circular route, where the amount of gas at stationi is
gas[i]
.You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from stationi 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点无法到达k点,那么从i~k的任意一点都无法到达k。同时若gas的总和大于cost的总和,则说明必然有解。
所以核心就是寻找所谓的start,设定tank变量存储当前gas和cost的差,当tank小于0,说明存在上述i~k的情况,便将start跳到tank之后。一轮检索之后,比较总的gas与cost,若大于等于0,则返回cost;小于0则意味着无法转一圈,则返回-1.
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start(0),total(0),tank(0);
for(int i=0;i<gas.size();i++) if((tank=tank+gas[i]-cost[i])<0) {start=i+1;total+=tank;tank=0;}
return (total+tank<0)? -1:start;
}
};
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start(0),total(0),tank(0);
for(int i=0;i<gas.size();i++) if((tank=tank+gas[i]-cost[i])<0) {start=i+1;total+=tank;tank=0;}
return (total+tank<0)? -1:start;
}
};
0 0
- 134. Gas Station Add to List
- [LeetCode]134.Gas Station
- LeetCode 134. Gas Station
- [Leetcode] 134. Gas Station
- 134. Gas Station
- [leetcode] 134. Gas Station
- Leetcode-134.Gas Station
- 134. Gas Station LeetCode
- 134. Gas Station
- Leetcode 134. Gas Station
- 134. Gas Station
- 134. Gas Station
- [LeetCode]134. Gas Station
- LeetCode 134. Gas Station
- leetcode 134. Gas Station
- LeetCode *** 134. Gas Station
- 134. Gas Station
- LeetCode 134. Gas Station
- 【神经网络与深度学习】【计算机视觉】SSD
- 数据分析和数据可视化(第一讲)
- 利用字符串和列表将两个通讯录文本合并为一个文本
- 如何配置二级缓存
- 【EJB体系结构】
- 134. Gas Station Add to List
- Python爬虫系列(一)初期学习爬虫的拾遗与总结
- openfire服务器
- ubuntu 14.04 server搭建+NVIDIA+CUDA+CUDNN+caffe+theano+tensorflow+keras+matlab
- 【神经网络与深度学习】【计算机视觉】YOLO2
- Codeforces 467B Fedor and New Game
- VS2012创建和使用DLL
- 文章标题
- CSU1100