134. Gas Station (Array; DP)
2015-10-08 15:49
627 查看
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
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.
思路:
1. 是否能travel around? =>只要gas[]加总的和 - cost[]加总的和 > 0,就能够。=>需要一个INT计算gas[]-cost[]的总合
2. 如何找到起点?如果到了某一站油不够,那么起点必须从它后面开始重新找。=>需要一个INT记录从找到的起点到目前为止的油量
时间复杂度O(n)
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.
思路:
1. 是否能travel around? =>只要gas[]加总的和 - cost[]加总的和 > 0,就能够。=>需要一个INT计算gas[]-cost[]的总合
2. 如何找到起点?如果到了某一站油不够,那么起点必须从它后面开始重新找。=>需要一个INT记录从找到的起点到目前为止的油量
时间复杂度O(n)
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int sum = 0, total = 0, len = gas.size(), index = -1; for(int i=0; i<len; i++){ sum += gas[i]-cost[i]; total += gas[i]-cost[i]; if(sum < 0){ index = i; sum = 0; } } return total>=0 ? index+1 : -1; } };
相关文章推荐
- 设计模式--代理模式
- 排序--看一眼就忘不了
- 图片入库后应该做的
- java输出调试技巧及Eclipse快捷键使用方法
- HDU 4337 King Arthur's Knights 它输出一个哈密顿电路
- D3学习教程
- Java序列化的几种方式以及序列化的作用
- git conflict
- 实验一报告
- linux下查看mysql版本
- 使用Chrome DevTools的Timeline和Profiles提高Web应用程序的性能
- swift之宏定义
- JVM中符号引用与直接引用
- lua中给表(table)重载运算符,使table之间可以互相加减乘除
- Excel导入异常Cannot get a text value from a numeric cell解决
- deeplearning系列(三)梯度检验
- Android基础: 数据存储(二):数据库存储和获取数据
- 大型网站架构与分布式架构
- Unity NavMesh导航网格 初级教程
- mongoose