leetcode笔记:Gas Station
2015-09-12 20:58
501 查看
一.题目描述
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.
环形路线上有N个加油站,每个加油站有汽油
二.题目分析
以下解法的时间复杂度为:
三.示例代码
几个处理结果:
四.小结
该题是比较有趣的一题,该方法只是多种方法中一种。
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.
环形路线上有N个加油站,每个加油站有汽油
gas[i],从每个加油站到下一站消耗汽油
cost[i],问从哪个加油站出发能够回到起始点,如果都不能则返回-1,最后题目提到解是唯一的。
二.题目分析
以下解法的时间复杂度为:
O(n),每个车站可加油量和每段距离的耗油量分别存放在
gas和
cost中,可以设置两个变量:
sum用于判断当前是否有足够的油量走到下一个加油站,若
sum<0,则需将出发车站前移一个车站;
remainingGas用于记录车开完整个过程后的油量。最终,判断
remainingGas是否大于零,是则返回初始车站的下标;若所有车站都出发都无法走完全程,则返回
-1。
三.示例代码
#include <vector> using namespace std; class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int remainingGas = 0; int resultIndex = 0; int sum = 0; for (size_t i = 0; i < gas.size(); ++i) // 对每个车站的情况进行遍历 { remainingGas += gas[i] - cost[i]; sum += gas[i] - cost[i]; if (sum < 0) { sum = 0; resultIndex = i + 1; } } if (remainingGas < 0) return -1; // 所有加油站的加油量小于消耗量 else return resultIndex; // 有解 } };
几个处理结果:
四.小结
该题是比较有趣的一题,该方法只是多种方法中一种。
相关文章推荐
- _25407739的博客 个人主页|我的博客
- 随手写了一个鸡肋的二叉树
- 神器
- systemd详解
- git push免密码
- 建造者模式(三):关于Director的进一步讨论,建造者模式总结
- SOCKET网络通信
- 第一次拿shell
- Mat中的depth、dims、channels、step、data、elemSize
- 自学QT之进度条
- 22_01_httpd虚拟主机
- C _数据结构 _线性表的顺序存储
- 学习日志---基本排序算法
- Android 使用ShardSDK实现社会化分享
- CentOS 7 之systemd管理
- Hadoop笔记十二之 java.io.IOException: expected org.apache.hadoop.io.LongWr
- 1102. Invert a Binary Tree (25)
- 街道最短路径问题
- 逆序数 HDOJ 4911 Inversion
- EF开发模式(EF基础系列篇9)