[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 ...
随机推荐
- 4.了解AngularJS模块和依赖注入
1.模块和依赖注入概述 1.了解模块 AngularJS模块是一种容器,把代码隔离并组织成简洁,整齐,可复用的块. 模块本身不提供直接的功能:包含其他提供功能的对象的实例:控制器,过滤器,服务,动画 ...
- Linux下编译安装Apache Http Server
Linux下编译安装Apache Http Server [TOC] 1.下载httpd-2.4.12.tar.bz2 wget http://mirror.bit.edu.cn/apache/htt ...
- Python 正则表达式:只要整数和小数
要求用户只能输入数字(包括整数和小数),如何用正则表达式验证用户输入? 有两种思路: 1. 给出正确格式的正则表达式,然后看输入是否合法. 2. 列出所有错误的输入,看输入是否非法. 对于思路1,想想 ...
- 【GoLang】GoLang 中 make 与 new的区别
make.new操作 make用于内建类型(map.slice 和channel)的内存分配.new用于各种类型的内存分配. 内建函数new本质上说跟其它语言中的同名函数功能一样:new(T)分配了零 ...
- wireshark 和 Httpwatch tcpdump
wireshark 功能强大,适用性高.过滤功能好. Httpwatch 功能单一,优缺点明显,但是非常适合抓取http交互的包,而且可以非常明确的显示出整个的交互过程. tcpdump linux ...
- mysql性能优化学习笔记-存储引擎
mysql体系架构 客户端(java.php.python等) mysql服务层(连接管理器.查询解析器.查询优化器.查询缓存) mysql存储引擎(innodb.myisam等) 存储引擎针对表而言 ...
- Java中对List集合内的元素进行顺序、倒序、随机排序的示例代码
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Test ...
- PHP中文字符串编码转换
2016年2月26日 16:47:13 星期五 情景: PHP从csv导入数据时乱码 $name = mb_convert_encoding($name, 'UTF-8', 'ASCII,GBK,GB ...
- shell 监控局域网的主机是否up
#!/bin/bash ;i<;i++)) ;do .$i>/dev/null #ping -c 172.31.0.30 ~172.31.0.59 ]] #if up $?==0 then ...
- FFmpeg-20160413-snapshot-bin
ESC 退出 0 进度条开关 1 屏幕原始大小 2 屏幕1/2大小 3 屏幕1/3大小 4 屏幕1/4大小 S 下一帧 [ -2秒 ] +2秒 ; -1秒 ' +1秒 下一个帧 -> -5秒 F ...