134. Gas Station | Java最短代码实现
java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料
保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。
原题链接:134. Gas Station
【思路1】
从末站开始,startStation和endStation均指向最后一站,一旦发现剩余的油量小于0,那么startStation前移——回去“加油”,直到油量大于等于0,那么endStation开始后移——继续前进。如果最后的剩余油量大于等于0,那么表示可以环游一周,startStation即为解。否则,不可以,返回 -1。
public int canCompleteCircuit(int[] gas, int[] cost) {
int startStation = gas.length - 1, endStation = gas.length - 1;
int travelCount = 0;
int totalRemain = 0, remain = gas[startStation] - cost[startStation];
while (travelCount++ < gas.length) {
totalRemain += remain;
if (totalRemain < 0 && --startStation >= 0) {
remain = gas[startStation] - cost[startStation];
} else {
endStation++;
remain = gas[endStation % gas.length] - cost[endStation % gas.length];
}
}
return totalRemain >= 0 ? startStation : -1;
}
16 / 16 test
cases passed. Runtime: 1
ms Your runtime beats 7.59% of javasubmissions.
【思路2】
假设startStation = 0,往后开,假设在第 i 站第一次总油量小于0,那么表示 0 至第 i - 1 站均不适合作为起始站,此时总剩余油量 remain1 < 0。那么将第 i 站作为起始站,同样的,一旦发现油量 remain2 < 0,那么就重设起始站。最后遍历完gas之后,如果 totalRemain >= 0,那么startStation就是起始站,并且[startStation, gas.length - 1]必然remain均大于0:
public int canCompleteCircuit(int[] gas, int[] cost) {
int startStation = 0, totalRemain = 0, remain = 0;
for (int i = 0; i < gas.length; i++) {
totalRemain += gas[i] - cost[i];
if (remain < 0) {
remain = gas[i] - cost[i];
startStation = i;
} else {
remain += gas[i] - cost[i];
}
}
return totalRemain >= 0 ? startStation : -1;
}
欢迎优化!
因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。
后续会有更多的精彩的内容分享给大家。
支付宝扫一扫
微信扫一扫
