Leetcode NO.134 Gas Station
2015-03-13 13:10
375 查看
本题题目要求如下:
There are N gas stations along a circular route, where the amount of gas at station i is
You have a car with an unlimited gas tank and it costs
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.
这题算是比较简单的一道题
就用这张图片来说明吧。。我的算法是寻找最低点。。也就是4,只有从4出发,才有可能避免出现负数点。。。
当然我上面画的是连续图,如果是用离散的话,会有一点小的出入,但总体是这个意思。。
代码如下:
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.
这题算是比较简单的一道题
就用这张图片来说明吧。。我的算法是寻找最低点。。也就是4,只有从4出发,才有可能避免出现负数点。。。
当然我上面画的是连续图,如果是用离散的话,会有一点小的出入,但总体是这个意思。。
代码如下:
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int concave_x = 0; int concave_y = 0; int remain = 0; int sz = gas.size(); for(int i = 0; i < sz; ++i) { remain = remain + gas[i] - cost[i]; concave_y = min(remain, concave_y); if (remain == concave_y) concave_x = i; } if (remain < 0) return -1; else return ((concave_x + 1) % sz); } };
相关文章推荐
- Leetcode-134-Gas Station C#
- Leetcode: Gas Station
- LeetCode:Gas Station
- leetcode Gas Station
- Leetcode_gas-station
- leetcode笔记:Gas Station
- [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。
- LeetCode - Gas Station
- LeetCode——gas station
- LeetCode-----------gas-station
- leetcode :Gas Station
- 【leetCode百题成就】Gas Station解题报告
- LeetCode2.1.21(Gas Station)
- [LeetCode]Gas Station
- [LeetCode]Gas Station
- LeetCode:Gas Station
- leetcode题目:gas-station 使用start/end方法的个人理解
- leetcode:Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station