leetcode之Gas Station
2014-05-16 11:27
281 查看
There are N gas stations along a circular route, where the amount of gas at station i is
You have a car with an unlimited gas tank and it costs
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.
这道题的代码实现并不难,关键是对思路的理解。关于思路,很多博客都说明了其中的两点,但我个人感觉还需要加上第三点才更有说服性。
一、从前往后遍历一遍,如果总消耗小于总供给,则不存在这样的一条路线,否则,存在,而且由题目可知存在且唯一。
二、从前往后遍历,如果A不能到达B(B是以A为起点第一个不能到达的地点),那么以A到B之间的所有点为起点都不能到达B,此时只需以B为起点重新判断。
三、假设循环路径为A、B、C、D、E、F,如果存在E——F——A,那么从E出发到达A时所剩的汽油一定不比从F出发到达A时所剩的汽油少,而继续往下走时,A到E的消耗比A到F的消耗还要少,所以如果存在唯一解的话起点只可能是E而不可能是E之后的点。
补充:借鉴循环连续最大子段和的思路,此题可以通过将数据连续存储两遍而将问题简化为非循环问题,这种思路也更加容易理解。
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.
这道题的代码实现并不难,关键是对思路的理解。关于思路,很多博客都说明了其中的两点,但我个人感觉还需要加上第三点才更有说服性。
一、从前往后遍历一遍,如果总消耗小于总供给,则不存在这样的一条路线,否则,存在,而且由题目可知存在且唯一。
二、从前往后遍历,如果A不能到达B(B是以A为起点第一个不能到达的地点),那么以A到B之间的所有点为起点都不能到达B,此时只需以B为起点重新判断。
三、假设循环路径为A、B、C、D、E、F,如果存在E——F——A,那么从E出发到达A时所剩的汽油一定不比从F出发到达A时所剩的汽油少,而继续往下走时,A到E的消耗比A到F的消耗还要少,所以如果存在唯一解的话起点只可能是E而不可能是E之后的点。
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int sum = 0,total = 0,index = 0; for(int i = 0; i < gas.size(); i++){ sum += gas[i] - cost[i]; total +=gas[i] - cost[i]; if(sum < 0) { index = i + 1; sum = 0; } } if(total < 0) return -1; return index; } };
补充:借鉴循环连续最大子段和的思路,此题可以通过将数据连续存储两遍而将问题简化为非循环问题,这种思路也更加容易理解。
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int len = gas.size(); vector<int>v(2*len); for(int i = 0; i < len; i++){ v[i] = gas[i] - cost[i]; v[i + len] = v[i]; } int sum = 0, index = 0,count = 0; for(int i = 0; i < 2*len; i++){ sum +=v[i]; count++; if(sum < 0){ sum = 0; index = i + 1; count = 0; } if(count == len){ return index; } } return -1; }
相关文章推荐
- [LeetCode] Gas Station
- LeetCode 之 Gas Station
- LeetCode - Gas Station 题解
- leetcode之Gas Station
- [leetcode] Gas Station java
- leetcode Gas Station
- LeetCode 134. Gas Station(加油站)
- leetcode-Gas Station
- LeetCode Gas Station
- Gas Station - Leetcode
- leetcode之Gas Station
- [leetcode]Gas Station @ Python
- leetcode——134——Gas Station
- Leetcode:Gas Station
- LeetCode Gas Station
- leetcode 134: Gas Station
- [LeetCode]Gas Station 最大子序列和,贪心
- [LeetCode] 774. Minimize Max Distance to Gas Station 最小化加油站间的最大距离
- LeetCode 774. Minimize Max Distance to Gas Station
- LeetCode (Gas Station)