[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 ...
随机推荐
- hdu1536&&hdu3023 SG函数模板及其运用
S-Nim Time Limit: 1000MS Memory Limit: 32768KB 64bit IO Format: %I64d & %I64u Submit Status ...
- ITIL与ITSM的联系与区别
1.ITIL(IT Infrastructure Library)是CCTA(英国国家计算机和电信局)于20世纪80年代末开发的一套IT服务管理标准库,它把英国各个行业在IT管理方面的最佳实践归纳起来 ...
- No handlers could be found for logger "keystoneauth.identity.generic.base"
一般是因为发现了多个keystone的url造成的.
- (转)关于Certificate、Provisioning Profile、App ID的介绍及其之间的关系
转自http://www.cnblogs.com/cywin888/p/3263027.html 刚接触iOS开发的人难免会对苹果的各种证书.配置文件等不甚了解,可能你按照网上的教程一步一步的成功申请 ...
- C# Winfrom 页面传值
2个窗体 Parent,Children 代码: Parent public partial class Parent : Form { public string parentValue = &qu ...
- Qt 使用sqlserver
1. pro 添加 QT +=sql 2. void MainWindow::connectSqlServer() { QSettings *setIni = new QSettings( ...
- 使用eclipse开发的兼容性配置
通常使用eclipse开发程序的时候,正常情况下放到Linux中运行一般是没有什么问题,最明显的就是编码问题,这个一般都会统一为utf-8,另外还有Windows和Linux的换行符不同的原因,还有当 ...
- Delphi xe5 手机开发经验(新手级别)
Delphi xe5 手机开发经验(新手级别) http://diybbs.zol.com.cn/1/34037_699.html http://www.delphitop.com/html/jiqi ...
- sql server 导出表结构
今天准备整理下手里面几个数据库,形成一个表结构文档,方便以后维护使用. 网上找到一个脚本还不错,小小的修改就满足了我的要求,执行完SQL脚本. 在结果就能看到数据库所有表的结构,这个时候只要全选,然后 ...
- sqlserver insert 存储过程
-- 根据表中数据生成insert语句的存储过程Create Proc proc_insert (@tablename varchar(256)) as ...