[LeetCode] Gas Station
Recording my thought on the go might be fun when I check back later, so this kinda blog has no intention to be read by others(its just for recording, not article). but if you insist, hope you enjoy it. if you find me wrong, please let me know, very appreciated!
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.
My first try:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int footPrint = ;
int gasMount = gas[footPrint];
while (gasMount-cost[footPrint] >= ){
footPrint = (footPrint+)% gas.size();
if (footPrint == ){
//return to first
return footPrint;
}
gasMount = gasMount - cost[footPrint] + cost[footPrint];
}
return -;
}
};
Test failed on:
| Input: | [1,2], [2,1] |
| Output: | -1 |
| Expected: | 1 |
Then I realized that I'v completely underastimate the complexity of this problem(of course). what the problem really want me to provide is a choice on which station to begin with so that we can complete the circuit!
like the test case above, gas=[1,2] cost=[2,1], then if we start at gas[0] we failed to do circle, but if we choose gas[1] to begin with, we first make to gas[0] left for 1 gas, then we refule at gas[0] to get 2 gas,
and then we can make it to gas[1], thats complete the circuit, so the program output 1, because this is where we begin with.
But you may wonder, there might be many choices which satisfy this condition, your right, but the NOTE told us, there is only one :), so with that understanding, I have something to work with.
Here I am again, but the problem still not solved:( here is the code:
My 2nd try:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int footPrint = ;
int gasMount = ;
for (int i=; i<gas.size(); i++){
footPrint = i;
gasMount = gas[footPrint];
while (gasMount - cost[footPrint] >= ){
gasMount -= cost[footPrint];
footPrint = (footPrint+)%gas.size();
gasMount += gas[footPrint];
if (footPrint == i){
return footPrint;
}
}
}
return -;
}
};
This is really looks like the anwser, I mean its a naive but worked version. it passed all the test until it meet the very large one....I think there might be thousands of elements in input array...
and the system throw out the Time Limit Exceeded error. damn! that make things even more complicated! That means this naive solution is not acceptable, we have to do it smart, algorithem is a bitch :p
And finally, I did not work out this problem, what a shame to faile my first leetcode challenge :( , anyway, I did search for anwsers and I really got some hint, also I stole some idea from others and
then implemented my own AC version.
My final anwser:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int total=;
for (int i=; i < gas.size(); i++){
int j=;
for (; j < gas.size(); j++){
total += gas[((i+j)%gas.size())] - cost[(i+j)%gas.size()];
if (total < ){
i +=j;
total = ;
break;
}
}
if (j==gas.size())return i;
}
return -;
}
This is a really nice approach which cost only O(n) time, If you think its O(n^2) by just simply looking at the double for loop, then you are wrong, mind that the j is pushing the i forward.
whenever total is less then 0, the elements which between i to j is no longer need to be checked again, so we simply skip them, in this way, theres actually only 1 loop occurred during the entire operation.
the thinking behind this algorithm is called Dynamic Programming, and this problem is very similar to Longest Consecutive Sequence problem, the difference is this one do a circuit.
For the purpose of enhancing what I'v learned, I decide to write down a snippet of code for solving Longest Consecutive Sequence problem.
int maxSum(int *a, int len){
int i, sum=, max=;
for (i=;i<len;i++){
if (sum >= ){
sum += a[i];
if (sum > max){
max = sum;
}
else{
sum = a[i];
}
}
return max;
}
[LeetCode] Gas Station的更多相关文章
- [LeetCode] Gas Station 加油站问题
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- [leetcode]Gas Station @ Python
原题地址:https://oj.leetcode.com/problems/gas-station/ 题意: There are N gas stations along a circular rou ...
- LeetCode: Gas Station 解题报告
Gas Station There are N gas stations along a circular route, where the amount of gas at station i is ...
- [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。
LeetCode上 Gas Station是比较经典的一题,它的魅力在于算法足够优秀的情况下,代码可以简化到非常简洁的程度. 原题如下 Gas Station There are N gas stat ...
- LeetCode——Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- [Leetcode] gas station 气站
There are N gas stations along a circular route, where the amount of gas at station i isgas[i]. You ...
- [LeetCode] 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]. You ...
- leetcode@ [134] Gas station (Dynamic Programming)
https://leetcode.com/problems/gas-station/ 题目: There are N gas stations along a circular route, wher ...
随机推荐
- 6 HandlerDescriptor 处理程序描述类——Live555源码阅读(一)基本组件类
这是Live555源码阅读的第一部分,包括了时间类,延时队列类,处理程序描述类,哈希表类这四个大类. 本文由乌合之众 lym瞎编,欢迎转载 http://www.cnblogs.com/oloroso ...
- django 的模板语言
1.模版的执行 模版的创建过程,对于模版,其实就是读取模版(其中嵌套着模版标签),然后将 Model 中获取的数据插入到模版中,最后将信息返回给用户. def current_datetime(req ...
- ubuntu 14 谷歌拼音输入法
帮人倒腾了下,顺便记录下: https://rivercitylabs.org/install-google-pinyin-on-ubuntu-14-04/ sudo apt-get install ...
- rpm包制作(待实验)
作者:firefoxbug 时间:July 18, 2014 rpm包命名规范 对于rpm包的命名符合如下规范. %{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}.rpm N ...
- Jquery Ajax处理,服务端三种页面aspx,ashx,asmx的比较
常规的Jquery Ajax 验证登录,主要有3种服务端页面相应 ,也就是 aspx,ashx,asmx即webserivice . 下面分别用3种方式来(aspx,ashx,asmx)做服务端来处理 ...
- Docker的安装配置及使用详解
基本概念 Docker 包括三个基本概念 镜像(Image) 容器(Container) 仓库(Repository) 先理解了这三个概念,就理解了 Docker 的整个生命周期. 1.docker安 ...
- Storm集成Kafka应用的开发
我们知道storm的作用主要是进行流式计算,对于源源不断的均匀数据流流入处理是非常有效的,而现实生活中大部分场景并不是均匀的数据流,而是时而多时而少的数据流入,这种情况下显然用批量处理是不合适的,如果 ...
- FASTREPORT 整理 (mtm)
DELPHI中用FASTREPORT制作报表 1.加载并存储报表 默认情况下,报表窗体同项目窗体构存储在同一个DFM文件中.多数情况下,无须再操作,因而你就不必采用特殊方法加载报表. 如果你决定在文 ...
- 10. javacript高级程序设计-DOM
1. DOM DOM(文档对象模型)是针对HTML和XML文档的一个API(应用程序接口) 1.1 节点层次 DOM可以将任何HTML和XML文档描绘成一个由多层节点构成的结构.节点分为几种不同的类型 ...
- 原:[eclipse启动错误] JVM terminated.Exit code=2
启动eclipse的时候忽然出现以下错误: 解决方案: 删除环境变量PATH或者Path中的 C:\ProgramData\Oracle\Java\javapath