[LeetCode] Gas Station
来源:互联网 发布:铁拳3知乎 编辑:程序博客网 时间:2024/05/16 11:02
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.
使用贪心算法。规律是,如果从某个加油站出发,如果可以到达的最远终点不是自身,那么从这个加油站到其最远终点之间的所有加油站都可以排除,直接以上一轮的终点为起点再开始考虑。因为如果以中途加油站为起点考虑,那样会损失从之前加油站来的时候余下的油的优势,就更不可能最后到达自身了。
如果这样一直考虑,最后终点过了最原始起点,说明所有的点都被考虑过了一遍。时间复杂度O(N)。
public int canCompleteCircuit(int[] gas, int[] cost) {int length = gas.length;int start;int k = 0; // start testing from the first stationwhile (true) {int sum = 0;start = k % length; // save the starting pointdo {sum += gas[k % length] - cost[k % length];k++;} while (sum >= 0 && k < start + length);// complete a cycleif (k == start + length && sum >= 0) {return k - length;}// test from the end that has not been reachedelse {if (k >= length)return -1;}}}
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- [LeetCode]134.Gas Station
- [Leetcode] Gas Station (Java)
- gas station leetcode
- Documentation/virtual/kvm/locking.txt
- HTML中的<!DOCTYPE>
- android.widget.Gallery
- 版本控制软件
- 分支限界法----旅行售货员问题
- [LeetCode] Gas Station
- NULL
- Android Studio 不自动弹起代码提示功能解决办法 do not auto popup code completion
- 如何在SAE上安装原版wordpress
- sqlplus "/ as sysdba" 连不上,报ora-01031:insufficient privileges解决方法
- 随机数——Linux C编程
- 09-DIV+CSS-流和盒子模型初识
- 排序 -- 归并排序
- ANR的一些数据总结