leetcode-gas station(2014.2.21)
来源:互联网 发布:java 函数式编程 编辑:程序博客网 时间:2024/06/07 06:57
暴力的方法需要O(n*n)的时间复杂度,即挨个使每个加油站作为起点,进行尝试。
改进的方法:先要对整体进行判断,即加油站油总量大于需要消耗的油的总量,则一定可以。
每当累积的油量不足以消耗,则当从该站的下一站作为起点,也就是说,这样的站点,尽量放在后边。遍历一次即可。
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start=0;
int gasSum=0;
int costSum=0;
int total=0;
int sum=0;
for(int i=0;i<gas.size();i++){
gasSum+=gas[i];
costSum+=cost[i];
}
if(gasSum<costSum) return -1;
for(int i=0;i<gas.size();i++){
sum+=gas[i]-cost[i];
if(sum<0){
start=(i+1)%cost.size(); sum=0;
}
}
return start;
}
};
0 0
- leetcode-gas station(2014.2.21)
- LeetCode 2.1.21 Gas Station
- LeetCode | Gas Station(加油站)
- Leetcode 134(Gas Station)
- LeetCode(134) Gas Station
- LeetCode 题解(46): Gas Station
- LeetCode OJ 之 Gas Station (加油站)
- [leetcode-134]Gas Station(java)
- LeetCode 134. Gas Station(加油站)
- leetcode:greedy:Gas Station(134)
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- HTML笔记——列表
- POJ2524
- PHP生成和获取XML格式数据
- 操作系统之PV操作
- unable to load virtualbox engine解决方案
- leetcode-gas station(2014.2.21)
- C++创建类必备的三个函数以及使用new所需要做的事
- MachineLearning(Hsuan-Tien Lin)第十一讲
- JAVA命令大全
- Winform中的Load事件处理
- leetcode-Word Search(2014.2.18)
- 自己动手写操作系统第二章 pmtest1.asm分析
- Hibernate Annotation 一对一主键关联
- Java中Vector和ArrayList的区别