leetcode-134-Gas Station
2017-12-12 21:00
417 查看
代码:
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function(gas, cost) {
var arr = [];
var curSum = 0;
var positiveSum = 0;
var positiveIndex = 0;
var index = gas.length - 1;
gas.forEach((item, index) => {
arr.push(item - cost[index])
});
while (index >= 0) {
if (arr[index] < 0) {
curSum = arr[index--];
while (curSum < 0 && index >= 0) {
curSum += arr[index--];
}
if (index < 0) {
if (curSum + positiveSum >= 0) {
return positiveIndex
}
else {
return -1
}
}
else {
positiveSum += curSum;
positiveIndex = index + 1;
curSum = 0;
}
}
else {
while (arr[index] >= 0 && index >= 0) {
positiveSum += arr[index];
positiveIndex = index--;
}
if (index < 0) {
return 0
}
}
}
return -1
};
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function(gas, cost) {
var arr = [];
var curSum = 0;
var positiveSum = 0;
var positiveIndex = 0;
var index = gas.length - 1;
gas.forEach((item, index) => {
arr.push(item - cost[index])
});
while (index >= 0) {
if (arr[index] < 0) {
curSum = arr[index--];
while (curSum < 0 && index >= 0) {
curSum += arr[index--];
}
if (index < 0) {
if (curSum + positiveSum >= 0) {
return positiveIndex
}
else {
return -1
}
}
else {
positiveSum += curSum;
positiveIndex = index + 1;
curSum = 0;
}
}
else {
while (arr[index] >= 0 && index >= 0) {
positiveSum += arr[index];
positiveIndex = index--;
}
if (index < 0) {
return 0
}
}
}
return -1
};
相关文章推荐
- LeetCode 134 Gas Station
- LeetCode(134) Gas Station
- [LeetCode 134] Gas Station
- LeetCode134—Gas Station
- LeetCode(134) Gas Station
- [Leetcode 134, Medium] Gas Station
- Leetcode 134(Gas Station)
- 【Leetcode】Gas Station #134
- leetcode——134——Gas Station
- leetcode 134: Gas Station
- LeetCode(134) Gas Station
- LeetCode 134 Gas Station
- [leetcode] 134 Gas Station(经典dp || 贪心)
- 【LeetCode-面试算法经典-Java实现】【134-Gas Station(加油站问题)】
- LeetCode 134. Gas Station(java)
- leetcode[134]Gas Station
- LeetCode134——Gas Station
- LeetCode 134 - gas station
- LeetCode 134 Gas Station
- leetcode || 134、Gas Station