LeetCode——Gas Station
2014-07-10 10:18
423 查看
There are N gas stations along a circular route, where the amount of gas at station i is
You have a car with an unlimited gas tank and it costs
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.
原题链接:https://oj.leetcode.com/problems/gas-station/
题目:在一个环上有N个加油站,站 i 有 gas[i] 的油。
你有一辆汽车有无限大小的油箱,它从站 i 到站 i+1 要耗cost[i] 的油。你以空油箱从其中的一个站出发。如果你转了一圈,返回起始油站的索引,否则返回-1.
思路:先计算车到达每个加油站时加油站的油量和汽车消耗的油量之差,如果之差小于0,则说明汽车至少要从下一站出发,因为从本站出发的话,就到达不了下一站。如果总的之差小于0,则车无法完成一圈。
public int canCompleteCircuit(int[] gas, int[] cost) {
int minus = 0, total = 0, index = -1;
for (int i = 0; i < gas.length; i++) {
minus += gas[i] - cost[i];
total += minus;
if (minus < 0) {
index = i;
minus = 0;
}
}
return total < 0 ? -1 : index + 1;
}
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.
原题链接:https://oj.leetcode.com/problems/gas-station/
题目:在一个环上有N个加油站,站 i 有 gas[i] 的油。
你有一辆汽车有无限大小的油箱,它从站 i 到站 i+1 要耗cost[i] 的油。你以空油箱从其中的一个站出发。如果你转了一圈,返回起始油站的索引,否则返回-1.
思路:先计算车到达每个加油站时加油站的油量和汽车消耗的油量之差,如果之差小于0,则说明汽车至少要从下一站出发,因为从本站出发的话,就到达不了下一站。如果总的之差小于0,则车无法完成一圈。
public int canCompleteCircuit(int[] gas, int[] cost) {
int minus = 0, total = 0, index = -1;
for (int i = 0; i < gas.length; i++) {
minus += gas[i] - cost[i];
total += minus;
if (minus < 0) {
index = i;
minus = 0;
}
}
return total < 0 ? -1 : index + 1;
}
相关文章推荐
- LeetCode 134. Gas Station(加油站)
- 【leetcode】Gas Station
- LeetCode Gas Station
- leetcode之Gas Station
- [leetcode]Gas Station
- leetcode——134——Gas Station
- Leetcode NO.134 Gas Station
- Leetcode:Gas Station
- leetcode 134: Gas Station
- [LeetCode] 774. Minimize Max Distance to Gas Station 最小化加油站间的最大距离
- LeetCode 774. Minimize Max Distance to Gas Station
- LeetCode之Gas Station
- 114_leetcode_Gas Station
- LeetCode - Gas Station
- Leetcode 134(Gas Station)
- leetcode -day9 Candy & Gas Station & Binary Tree Maximum Path Sum
- LeetCode 2.1.21 Gas Station
- leetcode || 134、Gas Station
- LeetCode(134) Gas Station
- leetCode(54):Gas Station