[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 ...
随机推荐
- __getattr__ 与动态属性
直接上代码 >>> class Test(object): ... def __getattr__(self,attr_name): ... setattr(self, attr_n ...
- Python sorted函数对列表排序
http://jingyan.baidu.com/article/f3ad7d0ffe8e1409c2345b48.html http://www.cnblogs.com/100thMountain/ ...
- MySQL表结构及数据的备份
1.Navicat for MySQL 选择要保存的表,右键转储SQL文件,导出的sql文件中包括表的定义和表的数据两部分. 其他办法: (1) create table dust select * ...
- scp和rsync限制传输速度
1.scp 限速100KB/s scp -l 1000 test root@192.168.1.104 此时的传输速率就是1M/8=100KB左右 2.rsync 限速100KB/s rsync -a ...
- LIGHTSWITCH 连接 MYSQL,中文字符不能保存----解决方法。
使用:dotConnect for MySQL () 作为 数据库连接的PROVIDER , 在 LIGHTSWITCH 中 引用外部的MYSQL 数据源. http://www.devart.co ...
- Unity3d 残影效果(狂拽炫酷叼炸天)
效果图,真的很叼啊 我根据别人的改进了一版,支持MeshFilter上的Mesh(需要确保Mesh的Read/Write是开启的否则不能正常工作) 非常感谢原作者给提供思路.http://blog.c ...
- linux下mysql开启关和重启
开启: /etc/init.d/mysql start关闭: /etc/init.d/mysql stop重启: /etc/init.d/mysql restart 查看字符集show variabl ...
- MyBatis之代理开发模式
1 mybatis-Dao的代理开发模式 Dao:数据访问对象 原来:定义dao接口,在定义dao的实现类 dao的代理开发模式 只需要定义dao接口,由mybatis产生dao接口的实现类. 1.1 ...
- JDBC题库
一. 填空题 JDBC ,是一种用于执行SQL语句的Java API,为多种关系数据库提供统一访问.它由一组用Java语言编写的类和接口组成. JDBC API:供程序员调用的接口与类,集 ...
- HTML标记语法之表格元素
语法与语义: <table>和</table>定义表格的开始和结束 <thead>和</thead>定义表格头部的开始和结束 <tbody> ...