leetcode_Gas Station
来源:互联网 发布:windows to go制作方法 编辑:程序博客网 时间:2024/06/03 22:51
描述:
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.
思路:
这是一个动态规划的题目,假设能跑完全程,最后邮箱中的油肯定还有剩余,由于是一个环形的路线,所以理论来讲,可以从任何地方开始。所以,可以用两个变量来表示这道题目,sum表示全程的油的剩余,而index来表示从何处开始。
1.从任何地方可以开始本次的行程,而sum+=gas[i]-cost[i],若sum<0,说明从index开始是不合适的,换成从i+1开始,直至结尾
2.若最后sum>=0,说明路线存在且以index为起点的路线为一个可行的路线。
代码:
public int canCompleteCircuit(int[] gas, int[] cost) { int sum=0,tempSum=0,num=0,stationNum=0; int len=gas.length; for(int i=0;i<len;i++) { num=gas[i]-cost[i]; sum+=num; tempSum+=num; if(tempSum<0) { stationNum=(i+1)%len; tempSum=0; } } if(sum>=0) return stationNum; return -1; }
0 0
- Leetcode_gas-station
- Leetcode_Gas Station
- leetcode_Gas Station
- leetCode_Gas Station
- Pets'Station
- shihuo station
- hdu4435charge-station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- rails mysql mongoid carrierware gridfs 实现图片上传功能
- Memcached使用整理
- iOS- 绘图教程
- 括号匹配问题
- Swing 中 JTextField事件 与 鼠标事件整合
- leetcode_Gas Station
- SimpleAdapter
- MongoDB GridFS 数据读取效率 benchmark
- JAVA练习-第4天 对象流与序列化
- iOS开发网络数据之AFNetworking使用(2.0)
- 分割字符串的AfxExtractSubString函数
- C++primer 5.4 赋值操作符(2.1 类型转换)
- IOS常用第三方框架 --- ASIHTTPRequest 网络请求
- Oracle的alter的一些用法