gas-station Java code
来源:互联网 发布:数据透视表 值 合计 编辑:程序博客网 时间:2024/06/13 09:33
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 costscost[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.
思路:统计全程走完油是否耗尽。没耗尽,就在remain出现小于零的地方作为开始。
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { if (gas == null || cost == null || gas.length <= 0 || cost.length <= 0) return -1; int index = -1, remain = 0, total = 0; for(int i = 0; i < gas.length; i++){ total += gas[i] - cost[i]; remain += gas[i] - cost[i]; // 如果本次剩余<0,说明不能由i走到i+1 if(remain < 0){ remain = 0; index = i; } } return total >= 0 ? index + 1 : -1; }}
阅读全文
0 0
- gas-station Java code
- CODE 131: Gas Station
- [Leetcode] Gas Station (Java)
- [leetcode] Gas Station java
- Gas Station (Java)
- [LeetCode][Java] Gas Station
- leetcode:Gas Station 【Java】
- leetcode 日经贴,python code -Gas Station
- leetcode134 Gas Station java 算法
- 【leetcode】134. Gas Station【java】
- [LeetCode] 134. Gas Station java
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- 数字证书原理,公钥私钥加密原理 -因为这个太重要了
- 购物车
- xss脚本执行
- 配置MS SQL Server用户权限
- 路由-标签切换格式2
- gas-station Java code
- 2017-10-19离线赛总结
- iOS点击空白处或点击背景收起键盘
- java DNS 缓存时间(成功时间和失败时间)代码
- UVa 10859 Placing Lampposts
- [待总结整理]python笔记
- QT程序打包发布
- svn安装
- 这可能是最好的性能优化教程(一)