Gas Station
来源:互联网 发布:java easyui tree例子 编辑:程序博客网 时间:2024/05/22 01:48
原题链接: https://leetcode.com/problems/gas-station/description/
题目: 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.
Solution: 令left[i] = gas[i] - cost[i],sum[i : j] = left[i] + left[i+1] +… +left[j]. 现在假设题目有解,并假设车从站i开出,能到达站k,但在到达站k+1的途中没有了,这说明sum[i : k+1] < 0, 但这时,对任意的j,当i <= j <= k,sum[i : j] >= 0都是成立的。所以,由于只有唯一的解,站i~k都不可能是起始站,因为对任意的t,当i <= t <= k,都有sum[t : k+1] < 0。这时,因为假设有解,我们只需继续往后遍历站k+1。直到找到一个站点x,使得站点x符合sum[x : gas.size()-1] > 0,这时,站点x可能是解,只是可能,因为前面假设了题目有解。
那怎么确定题目是否有解?若题目有解,那么sum[0 : gas.size()-1]肯定大于或等于0,而题目又保证有唯一解,那上述的站点x就是题目的解。若小于0,那么题目肯定无解。
class Solution {public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int n = gas.size(); int sum = 0, total = 0; int start_index = 0; for (int i = 0; i < n; ++i) { sum += (gas[i] - cost[i]); total += (gas[i] - cost[i]); if (sum < 0) { start_index = i + 1; sum = 0; } } return total < 0 ? -1 : start_index; }};
复杂度: 时间复杂度为O(n)。
- 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
- 个人提升:知识管理
- python 多进程
- jave学习笔记
- 获取当前相对绝对路径
- 讲下SpringMvc的核心入口类是什么,Struts1,Struts2的分别是什么
- Gas Station
- 前端学习笔记
- python 迭代器、生成器待续。。
- composer 自动载入的简单理解
- SpingMvc中的控制器的注解一般用那个,有没有别的注解可以替代
- 封装的OkHttpUtils,拦截器,gsonutils类,解绑(防止内内存泄漏)
- Spark核心数据模型RDD及操作
- Servlet总结-Request
- 计算天数(c语言)