Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。——贪心、转化
Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is 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.
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
}
};
最直观的思路
最直观的解法自然是O(n2) 时间复杂度的挨个尝试。这里不做讨论。
思路变化一
如果你是司机,你肯定会选这么样的一个站点:从这个站点出发,先遇到的站点都是给车加油大于耗油的,从而让车攒够足够的余油,来撑过剩下的那些耗油大于加油的站点。
对于站点 i,我们把 gas[i] - cost[i] 当作整体考虑,我们用diff[i] = gas[i] - cost[i] 表示从当前站点出发,到下一个站点后剩余的油量。
因此结合司机的经验,题目就是需要找出这么一个点,从这个点出发,diff的累加值能达到峰值。
想起了什么吗?这道题就是求diff[]数组上的 和最大连续子序列,这个最大子序列的起始点就是车的出发点!如果车从这儿开都不能做到油箱不空,那么这个题目就该返回-1了。
因此,这道题转化成了 求循环数组的最大子序列问题。
最大子序列问题,若max<0,则应重新开始累积,因为再叠加max+=a[i]<a[i],循环同时记录最大峰值Max以及更新该序列的起始点stmax。求最小序列则正好相反。
这种问题的求法,主要就是利用动态规划,求出diff[0] 到 diff[size-1]这个非循环数组上的最大子序列MAX和最小子序列MIN。然后比较MAX和 Total - MIN,选出较大值(Total为 diff数组所有元素和)。当然,我们要求的不是最大子序列的和,而是最大子序列的其实位置。因此,如果MAX 较大,返回MAX所代表的最大子序列的起始元素;否则,返回MIN所代表的最小子序列末尾的下一个元素。
参照这种思路,我们可以写出如下代码:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
if(gas.size() != cost.size()) return -;
if(gas.size() == ) return -;
int MAX = gas[] - cost[], MIN = gas[] - cost[], max = gas[] - cost[], min = gas[] - cost[];
int stmax = , stMAX = , endMIN = ;
int total = , diff = ;
for(int i = ; i < gas.size(); ++i){
diff = gas[i] - cost[i];
total += diff; if(max < ){
max = diff;
stmax = i; //stmax用来存储当前序列的起始点
}else max += diff;
if(max > MAX){
MAX = max;
stMAX = stmax; //stmax用来存储最大序列的起始点
} if(min > ) min = diff;
else min += diff;
if(min < MIN){
MIN = min;
endMIN = i; //endMIN用来存储最小序列的末尾点
}
}
return total < ? - : (MAX >= (total - MIN) ? stMAX : (endMIN+) % gas.size()); //通过比较 MAX 和 (total - MIN) 返回相应结果。
}
};
这样的解法的时间复杂度是 O(N)
在末尾可以发现,最后我们在通过比较 MAX 和 (total - MIN) 得出结果后,并没有模拟让车从所得站点跑一圈,来验证是否正确,而是直接通过比较 total 和 0的关系来确定是否有解。
如果Total >= 0,那么直接返回站点,如果Total < 0,返回-1。
也就是说,直接通过Total的值就可以来确定该题是否有解。
思路变化二
这道题最直观的思路,是逐个尝试每一个站点,从站 i 点出发,看看是否能走完全程。如果不行,就接着试着从站点 i+1出发。
假设从站点 i 出发,到达站点 k 之前,依然能保证油箱里油没见底儿,从k 出发后,见底儿了。那么就说明 diff[i] + diff[i+1] + ... + diff[k] < 0,而除掉diff[k]以外,从diff[i]开始的累加都是 >= 0的。也就是说diff[i] 也是 >= 0的,这个时候我们还有必要从站点 i + 1 尝试吗?仔细一想就知道:车要是从站点 i+1出发,到达站点k后,甚至还没到站点k,油箱就见底儿了,因为少加了站点 i 的油。。。
因此,当我们发现到达k 站点邮箱见底儿后,i 到 k 这些站点都不用作为出发点来试验了,肯定不满足条件,只需要从k+1站点尝试即可!因此解法时间复杂度从O(n2)降到了 O(2n)。之所以是O(2n),是因为将k+1站作为始发站,车得绕圈开回k,来验证k+1是否满足。
等等,真的需要这样吗?
我们模拟一下过程:
a. 最开始,站点0是始发站,假设车开出站点p后,油箱空了,假设sum1 = diff[0] +diff[1] + ... + diff[p],可知sum1 < 0;
b. 根据上面的论述,我们将p+1作为始发站,开出q站后,油箱又空了,设sum2 = diff[p+1] +diff[p+2] + ... + diff[q],可知sum2 < 0。
c. 将q+1作为始发站,假设一直开到了未循环的最末站,油箱没见底儿,设sum3 = diff[q+1] +diff[q+2] + ... + diff[size-1],可知sum3 >= 0。
要想知道车能否开回 q 站,其实就是在sum3 的基础上,依次加上 diff[0] 到 diff[q],看看sum3在这个过程中是否会小于0。但是我们之前已经知道 diff[0] 到 diff[p-1] 这段路,油箱能一直保持非负,因此我们只要算算sum3 + sum1是否 <0,就知道能不能开到 p+1站了。如果能从p+1站开出,只要算算sum3 + sum1 + sum2 是否 < 0,就知都能不能开回q站了。
因为 sum1, sum2 都 < 0,因此如果 sum3 + sum1 + sum2 >=0 那么 sum3 + sum1 必然 >= 0,也就是说,只要sum3 + sum1 + sum2 >=0,车必然能开回q站。而sum3 + sum1 + sum2 其实就是 diff数组的总和 Total,遍历完所有元素已经算出来了。因此 Total 能否 >= 0,就是是否存在这样的站点的 充分必要条件。
这样时间复杂度进一步从O(2n)降到了 O(n)。
基于这个思路,可以写出更加简洁的代码:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
if(gas.size() == || cost.size() == || gas.size() != cost.size()) return -;
int total = , sum = , start = ;
for(int i = ; i < gas.size(); ++i){
total += (gas[i] - cost[i]);
if(sum < ){ //发现油箱空了,从下一个站点尝试
sum = (gas[i] - cost[i]);
start = i;
}else
sum += (gas[i] - cost[i]);
}
return total < ? - : start; //用total判断start 是否是满足要求的解
}
};
这种解法其实依托于一个数学命题:
对于一个循环数组,如果这个数组整体和 SUM >= 0,那么必然可以在数组中找到这么一个元素:从这个数组元素出发,绕数组一圈,能保证累加和一直是出于非负状态。
转自:http://www.cnblogs.com/felixfang/p/3814463.html
Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。——贪心、转化的更多相关文章
- [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。
LeetCode上 Gas Station是比较经典的一题,它的魅力在于算法足够优秀的情况下,代码可以简化到非常简洁的程度. 原题如下 Gas Station There are N gas stat ...
- 134. Gas Station(数学定理依赖题)
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- 134. Gas Station leetcode
134. Gas Station 不会做. 1. 朴素的想法,就是针对每个位置判断一下,然后返回合法的位置,复杂度O(n^2),显然会超时. 把这道题转化一下吧,求哪些加油站不能走完一圈回到自己,要求 ...
- [LeetCode] Gas Station 加油站问题
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- 20. Candy && Gas Station
Candy There are N children standing in a line. Each child is assigned a rating value. You are giving ...
- [LeetCode] Minimize Max Distance to Gas Station 最小化去加油站的最大距离
On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., statio ...
- A1072. Gas Station
A gas station has to be built at such a location that the minimum distance between the station and a ...
- [leetcode greedy]134. Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- [leetcode]134. Gas Station加油站
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. Y ...
随机推荐
- python 中变量和对象
1. 在 python 中,类型属于对象,变量是没有类型的:a=[1,2,3] a="Runoob"以上代码中,[1,2,3] 是 List 类型,"Runoob&quo ...
- Python中变量的命名与使用(个人总结)
与众多编程语言一样,Python变量的命名有一定的规范: 变量名只能包含字母.数字.下划线且不能以数字开头.例如,num_1 为正确命名,而 1_num 则错误. 变量名不允许含空格,但是可以用下划线 ...
- DRF filter
filter 配置 fiter定义 自定义filter继承BaseFilterBackend,必须重写filter_queryset,返回值为过滤后的queryset filter在GenericAP ...
- 电子邮件中的to、cc、bcc
电子邮件中的to.cc(carbon copy)和bcc(blind carbon copy),分别是收件人.抄送.密送 to 收件人 你想要给其发邮件的人 cc 抄送人 cc和to是一样的,但是cc ...
- luogu3629 [APIO2010]巡逻
创造一个环出来,可以让环上的边都只访问一次. 对于 \(k=1\),答案就是树的直径两边连起来. 倘若 \(k=2\),那就先按照 \(k=1\) 的求一遍,然后我们发现,如果第二条加的边构成的环和第 ...
- centos 7 安装vmware 12
1.下载VMware 衔接地址 http://www.vmware.com/products/workstation/workstation-evaluation ,下载Linux版本的VMware. ...
- Android ScrollView嵌套GridView导致GridView只显示一行item
Android ScrollView嵌套GridView导致GridView只显示一行item Android ScrollView在嵌套GridView时候,会导致一个问题发生:GridView只显 ...
- lua-helloworld
write script file, a.lua: #!/usr/bin/lua print("hello world!") add excutable prperty to th ...
- zoj2112 主席树动态第k大 ( 参考资料链接)
参考链接: http://blog.csdn.net/acm_cxlove/article/details/8565309 http://www.cnblogs.com/Rlemon/archive/ ...
- NOIP[2015] 运输计划(codevs 4632)
题目描述 Description 公元 2044 年,人类进入了宇宙纪元.L 国有 n 个星球,还有 n−1 条双向航道,每条航道建立在两个星球之间,这 n−1 条航道连通了 L 国的所有星球.小 P ...