Gas Station
来源:互联网 发布:linux清理目录 编辑:程序博客网 时间:2024/05/09 14:19
环路上n个加油站,每个加油站的储油是gas[i],到下一个加油站消耗的油是cost[i], 问:从哪个加油站开始走能回到起点?
直接的思路,一个一个加油站作为起点的试,往下走,一旦到某个加油站累加的油不够到下一个加油站T,这个起点就不行,换下一个,O(n^2)的复杂度。
进一步的思路是,一旦到某个加油站累加的油不够到下一个加油站T,之前走过的加油站都可以排除,因为都走不到T。
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {int start = 0, sum = 0, total = 0;for (int i = 0; i < gas.size(); ++i) {total += gas[i] -cost[i];sum += gas[i] -cost[i];if (sum < 0) {start = i + 1;sum = 0;}}return total >= 0 ? start : -1;}
0 0
- 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
- CLIF 数据库 和 VIVID 数据库
- hdu1787 GCD Again
- Java知识点小结
- zz
- 二项分布期望和方差的公式推导
- Gas Station
- Cakephp: [MissingTableException] 错误信息 解决方法
- poj 2965 The Pilots Brothers' refrigerator(dfs 枚举 +打印路径)
- IOS 内存管理 案例篇 MBProgressHUD
- OVa OJ 488 - Triangle Wave
- Eclipse 安装最新SVN插件
- Windows 9没有了,Windows 10发布了
- 咨询系统的检索功能——Lucene
- Java输入输出(1)