Gas Station
来源:互联网 发布:ubuntu下修复win10引导 编辑:程序博客网 时间:2024/05/08 07:01
题目原型:
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.
基本思路:
遍历一圈,如果说剩下的油和待加的油能够走过这一站的话则继续,否则改变起点继续,当起点回到原来走过的点时表示不能
public int canCompleteCircuit(int[] gas, int[] cost){if(gas.length==0||gas==null)return -1;if(cost.length==0||cost==null)return 0;int index = 0;int rest = 0;//还剩多少油int count = 0;//走过的长度int startIndex = 0;//起始点int len = gas.length;boolean isCircle = false;//记录是否回到了曾经走过的点while(count<len){if(rest<0||rest+gas[index]<cost[index]){startIndex = (index+1)%len;//起点回到曾经走过的点那么就说明不能通过if(isCircle)return -1;count = 0;}else{rest = rest + gas[index] - cost[index];count++;}if(index+1>=len)isCircle=true;index = (index+1)%len;}return startIndex;}
绕一圈。
0 0
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- 东方人共同的任何一条任何人一条
- 基于报表范围
- C语言基础五_static和extern
- 它可以很容易使
- 九度OJ--1090--路径打印
- Gas Station
- oracle 反联结 NOT IN、NOT EXISTS
- 安装win7时提示:“缺少所需的CD/DVD驱动器设备驱动程序。…………”
- css 收缩
- 服务器推送技术原理分析及dwr框架简单的使用
- 经典智力题:小明一家过桥
- JS eval(function(p,a,c,k,e,r){e=function(c)*****解密
- iOS 7 教程:定制iOS 7中的导航栏和状态栏
- 在决定使用ClickOnce发布你的软件前,应该知道的一些事情(一些常见问题解决方法)