[LeetCode]Gas Station
2016-02-12 17:09
302 查看
新年啦,大家新年快乐~~
由于新年呢,所以最近很少做题,今天终于有时间可以打打代码了
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.
比较简单的题目,只要想到一个策略就好了.(貌似是贪心?)
上代码了,其实主要思想就是看下当前的汽油够不够用.
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int g=0; int c=0; int tg=0; int tc=0; int ret=0; boolean flag = false; for(int i=0;i<cost.length;i++){ g+=gas[i]; c+=cost[i]; tg+=gas[i]; tc+=cost[i]; if(gas[i]>cost[i] && !flag){ ret = i; flag = true; } if(tg<tc){ tg=0; tc=0; flag = false; } } if(c<=g) return ret; return -1; } public static void main(String[] args) { Solution s = new Solution(); int[] gas = new int[]{2}; int[] cost = new int[]{2}; System.out.println(s.canCompleteCircuit(gas, cost)); } }
相关文章推荐
- 从初识Linux到离不开系列(四)循序渐进
- 相当重要---部署OGG对Oracle Database 补丁的要求
- 算法学习--贪心算法
- Python教程学习简记8--Python 高阶函数 map/reduce filter sorted
- 深入理解Java虚拟机----(十一)线程安全与锁优化
- 舍身喂虎
- 后缀数组
- 2.ORM思想
- FMDB初步使用小结
- debian/ubuntu/deepin中Harminv 编译与安装
- HDU3466(01背包变种)
- 欢迎使用CSDN-markdown编辑器
- 将数字字符串转化为对应数字输出(不考虑溢出)
- The Java™ Tutorials — Concurrency :Synchronized Methods 同步方法
- Debian下配置LAMP环境
- 游戏开发中的数学和物理算法
- 把cocos2dx 2.2的项目移植到 cocos2dx 3.8
- hdu 4857 逃生
- QQ界面
- Translate this app.config xml to code? (WCF) z