leetcode gas-station【最大序列变形】
2017-04-12 11:40
351 查看
There are N gas stations along a circular route, where the amount of gas at stationi isgas[i].
You have a car with an unlimited gas tank and it costscost[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
百度题号,说到是最大序列的变形,然后自己想:
最大序列咋求的?从开头开始算累加和,发现小于0,前面都不要了,从当前位置重新加和,因为某段和是负数说明这段不会对于最大序列做贡献。
这个题也一样,某段如果是负数说明放结尾,要么就是根本没有可行解。
从0开始(这点我得吐槽一下,leetcode什么玩意,连个示例都没有,都不知道0开始还是1开始)
三个变量pos,sum,tmp分别表示开始点,总和,当前段的和。
如果发现某一段和是负数就清零tmp,pos换成下一个点
最后不要忘记sum+=tmp
判断sum值是否大于等于0
You have a car with an unlimited gas tank and it costscost[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
百度题号,说到是最大序列的变形,然后自己想:
最大序列咋求的?从开头开始算累加和,发现小于0,前面都不要了,从当前位置重新加和,因为某段和是负数说明这段不会对于最大序列做贡献。
这个题也一样,某段如果是负数说明放结尾,要么就是根本没有可行解。
从0开始(这点我得吐槽一下,leetcode什么玩意,连个示例都没有,都不知道0开始还是1开始)
三个变量pos,sum,tmp分别表示开始点,总和,当前段的和。
如果发现某一段和是负数就清零tmp,pos换成下一个点
最后不要忘记sum+=tmp
判断sum值是否大于等于0
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int num=gas.size(); int sum=0,tmp=0; int pos=0; for(int i=0;i<num;i++) { tmp+=gas[i]; tmp-=cost[i]; if(tmp<0) {pos=i+1;sum+=tmp;tmp=0;} } sum+=tmp; if(sum>=0)return pos; else return -1; } };
相关文章推荐
- [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。
- [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。
- [LeetCode]Gas Station 最大子序列和,贪心
- LeetCode-Gas Station-加油站-最大子串算法应用
- Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法
- Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。——贪心、转化
- [LeetCode] 774. Minimize Max Distance to Gas Station 最小化加油站间的最大距离
- hdu 1243 反恐训练营(dp 最大公共子序列变形)
- LeetCode:Gas Station
- LeetCode:Gas Station
- LeetCode134:Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- [LeetCode] Gas Station
- [Leetcode] Gas Station (Java)
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- 【Leetcode】Gas Station
- LeetCode: Gas Station