[Leetcode]-Gas Station
2015-07-22 19:40
495 查看
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.
Hide Tags: Greedy
题目:循环一圈的道路上有gasSize个加气站gas[gasSize],从i到i+1加气站需要耗费cost[i]的气,要求可以从其中任意一个加气站出发,只要能保证回到出发点。
思路:贪恋算法。
第一次循环:从gas[0]加气站出发i 从0-> gasSize-1, 挨站判断是否能到第i站,over 为每到一站后剩余的燃气,over 为负数说明骑车到不了当前站i,当发现到不了的情况后当前站,马上就将当前站i作为出发点,over清零,重新开始向前走。
第二次循环:当然有可能走完一圈后还不能判断的,因为有可能起点并不是gas[0],所以还需要继续向前走,直到gas[start ],期只要有出现到不了的情况这判断为-1。如果能到最后判断over是否大于0,大于0则说明能到,否则返回-1。
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.
Hide Tags: Greedy
题目:循环一圈的道路上有gasSize个加气站gas[gasSize],从i到i+1加气站需要耗费cost[i]的气,要求可以从其中任意一个加气站出发,只要能保证回到出发点。
思路:贪恋算法。
第一次循环:从gas[0]加气站出发i 从0-> gasSize-1, 挨站判断是否能到第i站,over 为每到一站后剩余的燃气,over 为负数说明骑车到不了当前站i,当发现到不了的情况后当前站,马上就将当前站i作为出发点,over清零,重新开始向前走。
第二次循环:当然有可能走完一圈后还不能判断的,因为有可能起点并不是gas[0],所以还需要继续向前走,直到gas[start ],期只要有出现到不了的情况这判断为-1。如果能到最后判断over是否大于0,大于0则说明能到,否则返回-1。
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) { int i = 0; int over = gas[0]; int start = 0; if(gasSize == 1) return (gas[0] >= cost[0]) ? 0 : -1; for(i=1;i<gasSize;i++) { over = over - cost[i-1]; if(over < 0) { start = i; over = 0; } over = over + gas[i]; } over = over - cost[gasSize-1]; for(i=0;i<start;i++) { if(over < 0) { return -1; } over = over + gas[i] - cost[i]; } return (over >= 0) ? start : -1 ; }
相关文章推荐
- 自用工具记录
- 【翻译】如何创建Ext JS暗黑主题之二
- 总结个人2015提高前端效率的方法和工具
- 不带括号的简单四则运算
- HDU 5296 Annoying problem LCA+树状数组
- Reproducible Research in Computational Science
- C#缓存的一点想法及测试
- Js_字体滚动换颜色
- 使用css实现圆角图形绘制
- 事务隔离级别
- 史上最全 前端开发面试问题及答案整理 http://segmentfault.com/blog/trigkit4/1190000002562454
- spring中取出ApplicationContext
- 数据结构与算法分析1.8
- 离别
- hadoop安装和hadoop pipes编程说明
- 仿JD商城UI布局达到90%
- 1234 开门人和关门人
- 青年歌手大奖赛_评委会打分
- 【翻译】如何创建Ext JS暗黑主题之二
- hdu 5294 Tricks Device(15多校第一场1007)(spfa+最小割)