leetCode练习(134)(
来源:互联网 发布:mysql ocp认证费用 编辑:程序博客网 时间:2024/06/05 08:09
题目:Gas Station
难度:MEDIUM
问题描述:
There are N gas stations along a circular route, where the amount of gas at stationi is
gas[i]
.You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from stationi 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.
解题思路:
1.如果gas和大于cost和,必定有解。
2.从i开始,如果到k时,gas和小于cost和,那么解必定不在I和k之间(包含两端)
有了上面两点,题目就很容易解了,代码如下:
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int total = 0; int len = gas.length; for(int i=0;i<len;i++){ total +=gas[i]-cost[i]; } if(total<0)return -1; for(int i=0;i<len;i++){ int rest=0; int index=i; int count=0; while(!(rest<0)&&count<len){ rest +=gas[index]-cost[index]; if(rest<0){ break; } index++; count++; if(index==len) index=0; } if(count==len) return index; else i=index; } return -1; }}
0 0
- leetCode练习(134)(
- leetCode练习(7)
- leetCode练习(9)
- leetCode练习(2)
- leetCode练习(14)
- leetCode练习(3)
- leetCode练习(4)
- leetCode练习(19)
- leetCode练习(18)
- leetCode练习(5)
- leetCode练习(15)
- leetCode练习(20)
- leetCode练习(21)
- leetCode练习(16)
- leetCode练习(17)
- leetCode练习(11)
- leetCode练习(24)
- leetCode练习(22)
- Maven 入门、常用命令、扩展及配置
- Java 方法参数的变化
- hdu1381 hash
- Apache Httpclient4.5学习笔记
- UNITY新手小游戏
- leetCode练习(134)(
- 计算FLT_MAX的整数位长度
- 利用Lambda解决蓝桥杯【消除尾一】问题
- 练习项目之---jdbc对面的女孩看过来
- cpp——与c之不同——指针
- linux下的基本操作02(文件相关命令)
- javaee 学习路线
- 排序算法(冒泡、选择、插入)
- 手机信息页面设置