您的位置:首页 > 其它

每日AC--gas-station--LeetCode

2017-12-06 10:29 489 查看

每日AC--gas-station--LeetCode


题目描述

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.

AC代码

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int len = gas.length;
for(int i = 0; i < len; i++){
if(canComplete(i,gas,cost)){
return i;
}
}
return -1;
}

public boolean canComplete(int start, int[] gas, int[] cost){
int len = gas.length;
int total = 0;
for (int i = start; i < len + start; i++) {
if (total + gas[i % len] < cost[i%len]) {
return false;
} else {
total = total + gas[i % len] - cost[i%len];
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: