[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 ...
随机推荐
- phpcms评论框iframe无法自适应问题
问题背景: 之前用友言的时候改过网站的ip地址,改成127开头的了.但是协同开发的时候别人用的还是localhost. 结果在用评论的时候iframe死活不能自适应,看了一下源代码v9本身已经写过if ...
- Linux查看硬盘型号
Linux查看硬盘型号 -- :: 分类: 服务器与存储 请先确定服务器是否有配 RAID. 如果有RAID,请通过对应的RAID管理(监控)工具查看,例如LSI的MegaCli: # /opt/Me ...
- 保存字符串到手机SDcard为txt文件
try { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File sdCardDir ...
- mysql性能优化学习笔记-参数介绍及优化建议
MySQL服务器参数介绍 mysql参数介绍(客户端中执行),尽量只修改session级别的参数. 全局参数(新连接的session才会生效,原有已经连接的session不生效) set global ...
- Java for LeetCode 218 The Skyline Problem【HARD】
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city whe ...
- sql语句全集
--删除外键alter table AdItem drop constraint AdOrder_AdItem_FK1(外键名称) --增加外键alter table AdItem add const ...
- Python~list,tuple^_^dict,set
tuple~(小括号) list~[中括号] 和list比较,dict有以下几个特点: dict~{‘key’:value,} set~set([1,2,3]) tuple一旦初始化就不能修改~指向不 ...
- nyoj756_重建二叉树_先序遍历
重建二叉树 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描述 题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!). 输入 输入有多组数 ...
- JAVA中的Calendar得到当前时间的年份、月份、日期
import java.util.Calendar; public class CalendarTest { public static void main(String[] args) ...
- 自定义循环滑动的viewpager
今天和大家分享一下如何定制一个可以循环滑动的viewpager.其实今天更重要的提供一种组件化思想,当然你可以理解为面向对象思想. 吐槽一下网上流行的实现方式吧(为了方便说明,下文称之为方式A),方式 ...