Gas Station
来源:互联网 发布:淘宝客现状 编辑:程序博客网 时间:2024/06/06 19:13
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 gastank and it costs cost[i]
of gas to travel from station i to its next station (i+1). Youbegin the journey with an empty tank at one of the gas stations.
Return the starting gas station's indexif you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
思路:首先想到的方法就是O(n^2)遍历两遍。搜了一下发现有更巧妙的方法,用两个变量来控制。第一个变量total负责一直累加gas[i]-cost[i],如果加到最后total>=0,说明肯定全局是有解的,但是不能判断出来到底是从哪里出发导致的有解;第二个变量sum就非常重要了,通过它来寻找start point在哪里。找的思路很简单,肯定是在sum<0的后一个index开始,这个要好好揣摩一下。Sum不关注到底有没有全局解,它只负责记录从i=0到i=n-1这个过程中最后一个导致sum<0的index。如果最后total>=0,那么index+1就为正确的起始点;如果最后total<0,那么sum记录的index也没用了,就是返回-1。
Ref:http://blog.csdn.net/lbyxiafei/article/details/12183461
class Solution {public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { if (gas.size() == 0 || cost.size() == 0){ return -1; } int total = 0, sum = 0, index = -1; for (int i = 0; i < gas.size(); i++) { sum += gas[i] - cost[i]; total += gas[i] - cost[i]; if (sum < 0) { sum = 0; index = i; } } return total >= 0 ? index + 1: -1; }};
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Trapping Rain Water
- java内部类回顾之一般内部类实现多继承和封装性
- 用迭代法求平方根
- STL简单构成
- Mongodb–journal探究
- Gas Station
- Jdk1.7环境变量的配置
- poj3278 Catch That Cow(BFS)
- 网页任意浮动广告
- 结构体(struct)的使用、内存分布以及字节对齐测试总结
- Palindrome Partitioning II
- 猜图项目全部代码
- Android 官网教程
- js中浮点型是如何运算