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 ...
随机推荐
- Onenote代码高亮的实现方法
最终效果图 最终的效果图如下: VBA的编写参考 主要参考的是这篇博客中的思路:如何在Word中排出漂亮的代码 将VBA脚本复制到Word中并设置快捷键 Alt+F11 打开Word中的 VBS,将下 ...
- pycharm添加wordcloud模块时报错:error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
windows 7 32bit python3.6.3 32bit pycharm2018社区版 32bit 问题说明: 添加wordcloud模块时报错:error: Microsoft Visua ...
- Python 前端 Html基础
概述 HTML是英文Hyper Text Mark-up Language(超文本标记语言)的缩写,他是一种制作万维网页的标准语言.相当于定义统一 的规则.大家都来遵守它,这样就可以让浏览器根据标记语 ...
- Java-将字符串转为数字
package com.tj; public class MyClass implements Cloneable { public static void main(String[] args) { ...
- 100个直接可以拿来用的JavaScript实用功能代码片段(转)
把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取2.原生JavaS ...
- Luogu【P1901】发射站(单调栈)
题目链接 题目说明比自己矮的塔收不到自己的能量,摆明了就是单调栈呗. 把比自己矮的全都从栈里弹出去,于是碰到第一个比自己高的.让他接受自己发射的能量. 当然由于发射站发射的能量有两个方向,所以正反两遍 ...
- 怎么创建SpringBoot项目
上述中讲到了怎么创建SpringBoot项目,那么现在就来介绍下SpringBoot配置文件的两种格式yml和properties 首先呢发上一份application.properties 在放上一 ...
- 常州模拟赛d3t1 神在夏至祭降下了神谕
题目描述 我们村子在过去的400年中,断绝与下界的接触,过着自给自足的生活. 夏至祭是一场迎接祖灵于夏季归来,同时祈求丰收的庆典. 村里的男人会在广场上演出夏之军和冬之军的战争.夏之军会打倒冬之军的大 ...
- 【离散化树状数组】Nordic Collegiate Programming Contest G.Galactic Collegiate Programming Contest
#include<bits/stdc++.h> using namespace std; typedef long long ll; int n,m; ; struct node { in ...
- uva 10870 递推关系矩阵快速幂模
Recurrences Input: standard input Output: standard output Consider recurrent functions of the follow ...