134. Gas Station
2016-07-25 03:17
405 查看
134. Gas Station
There are N gas stations along a circular route, where the amount of gas at station i isgas[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
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int start = 0; //start from start while(start<gas.length) { int net = gas[start] - cost[start]; if(net < 0) { ++start; continue; } int current = start; int sum = net; int count = 1; //already visit current, can start the journey with sum while(count < gas.length) { ++current; //go to the next stop if(current == gas.length) current = 0; sum += gas[current] - cost[current]; if(sum<0) { if(current + 1 <= start) //fix the case gas[2,4] with cost[3,4] return -1; start = current + 1; //start from next one. break; } ++count; } if(count == gas.length) return start; } return -1; } }
Simpler solution:
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int start = 0, total = 0, tank = 0; //if car fails at 'start', record the next station for (int visited = 0; visited < gas.length; ++visited) { tank += gas[visited] - cost[visited]; if (tank < 0) { start = visited + 1; total += tank; tank = 0; } } return (total + tank < 0) ? -1 : start; } }
相关文章推荐
- 前端开发:css技巧,如何设置select、radio 、 checkbox 、file这些不可直接设置的样式 。
- XML序列化与反序列化+自定义XML注解框架XmlUtils
- 显示访问IP
- ART世界探险(6) - 流程控制指令
- QWidget可以设置QStyle,它可以绘制很多东西(具体内容没研究,待续)
- CodeForces 197D Infinite Maze (BFS+状态压缩)
- android中dip、px相互换算
- struts2: tag s:property must be empty, but is not
- 练手程序120个(转载)
- 如果获取设备的的分辨率、屏幕尺寸、像素密度?
- Ofbiz模块加载机制即创建独立模块(脱离热部署)
- react native白屏及性能优化
- 相册管理系统
- 关于大小端字节序
- jquery ajax的参数以及使用方法详解
- 处理事件的方式:两种类的覆盖处理(自己管理,覆盖专用事件函数;自己统一管理,覆盖QWidget::Event通用函数),一种对象的处理(父控件统一管理,即安装过滤器),两种全局处理(QCoreApplication安装过滤器;覆盖notify方法)
- [React Native] Passing data when changing routes
- 我接下来要走的基础路
- PHP的51个Memcached方法(1-11)
- 368. Largest Divisible Subset