[Leetcode]Gas Station
来源:互联网 发布:中国木制品数据 编辑:程序博客网 时间:2024/06/03 19:51
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.
Note:
The solution is guaranteed to be unique.
class Solution {public: /*algorithm: for each start index,check whether it can reach full time O(n*n), TLE error */ bool canTravel(vector<int>& gas, vector<int>& cost,int start){ int sum = 0,n = gas.size(); for(int i=0;i < n;i++){ sum += gas[start] - cost[start]; if(sum < 0)return false; start = (start+1)%n; } return true; } int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int index = -1; for(int i = 0;i < gas.size();i++){ if(canTravel(gas,cost,i)){ index = i; break; } } return index; }};
class Solution {public: /*algorithm:greedy time O(n) */ int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int index = 0; int sum = 0,n = gas.size(),total=0; for(int i = 0;i < n;++i){ sum += gas[i] - cost[i]; total += gas[i] - cost[i]; if(sum < 0){ index = (i+1)%n; sum = 0; } } return total >= 0?index:-1; }};
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
- 【建议112--笔记】受检异常和非受检异常
- Longest Palindromic Substring
- 批量修改文件后缀名
- C语言swap函数总结
- 两台电脑怎么共享文件
- [Leetcode]Gas Station
- 重新学习COCOs2D-X版本2.2.3开始---第一篇引擎的游戏入口
- POJ 1089 解题报告
- printf( )的格式字符
- NSDate NSString NSArray NSDictionary 数据类型相互转换
- fs4412开发板学习笔记(九)
- container-with-most-water
- 一些实用PHP代码片段
- Two Sum