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解法。——贪心、转化的更多相关文章

  1. [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。

    LeetCode上 Gas Station是比较经典的一题,它的魅力在于算法足够优秀的情况下,代码可以简化到非常简洁的程度. 原题如下 Gas Station There are N gas stat ...

  2. 134. Gas Station(数学定理依赖题)

    There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...

  3. 134. Gas Station leetcode

    134. Gas Station 不会做. 1. 朴素的想法,就是针对每个位置判断一下,然后返回合法的位置,复杂度O(n^2),显然会超时. 把这道题转化一下吧,求哪些加油站不能走完一圈回到自己,要求 ...

  4. [LeetCode] Gas Station 加油站问题

    There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...

  5. 20. Candy && Gas Station

    Candy There are N children standing in a line. Each child is assigned a rating value. You are giving ...

  6. [LeetCode] Minimize Max Distance to Gas Station 最小化去加油站的最大距离

    On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., statio ...

  7. A1072. Gas Station

    A gas station has to be built at such a location that the minimum distance between the station and a ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. Luogu 2216 [HAOI2007]理想的正方形 (单调队列优化)

    题意: 给出一个 N×M 的矩阵,以及一个数值 K ,求在给定的矩阵中取出一个 K×K 的矩阵其中最大值减去最小值的最小值. 细节: 没有细节来发暴力走天下,20分也是分啊~~~ QAQ. 分析: 感 ...

  2. 关于网络IP地址的分类

    一.IP地址的分类 众所周知,IP地址都是以点号.分为4段来表示.不同类的IP前几位的表示含义也不尽相同. 1.A类IP [网络地址] 第一位表示网络地址,且第一个字节的第一位必须以0开头.依据此原则 ...

  3. strcat strcpy 源代码,用指针去实现

    15. 指针实现 strcmp函数     •    int newStrcpy(char *p, char *q)     •    {     •        while(*p ==*q) { ...

  4. 去掉WordPress顶部工具条

    WordPress为了方便管理员,或者登陆用户快速的从前台进入后台来管理网站,在WordPress网站顶部强制加入了一个工具条(admin bar),而且默认是对所有登陆用户都显示的,有时候看着挺烦心 ...

  5. wlan

    一.概述 CSMA/CD    --->以太网介质 CSMA/CA------->无线介质 IEEE----->802.11   a  b  g  e  f   h  i  j 分类 ...

  6. [android开发篇]安装android sdk的时候请注意

    第二就是: 如果要国内镜像的话: 3.大连东软信息学院镜像服务器地址: http://mirrors.neusoft.edu.cn  端口:80 随便选择一个就行啦.这里我选择的是第三个站点,即大连东 ...

  7. Nginx出现403 forbidden(Permission denied)报错的四种方法

    查看nginx的error.log日志.打开日志出现Permission denied: 1.启动用户和nginx的工作用户不一致所致 查看nginx的启动用户,发现是www,而为是用root启动的 ...

  8. BZOJ 2300 [HAOI2011]防线修建 ——计算几何

    只需要倒着插入,然后维护一个凸包就可以了. 可以用来学习set的用法 #include <map> #include <set> #include <cmath> ...

  9. POJ 2699 The Maximum Number of Strong Kings ——网络流

    一定存在一种最优方案,使得分数前几个人是SK 所以我们可以二分答案或者枚举,然后就是经典的网络流建模. 另:输入很Excited #include <cstdio> #include &l ...

  10. idea16使用maven命令clean、编译、打包jar或者war

    项目环境:idea16+jdk1.7+maven-3.3.9 项目说明:编写简单的java类,使用maven命令生成jar包,然后执行------->"java  -classpath ...