使用一艘船救人,每次最多只能救两人,请问最少要几次
这是左右节点法。
var numRescueBoats = function (people, limit) {
people.sort((a, b) => a - b)
var left = 0;
var right = people.length - 1;
var boats = 0, track = []
track.add = function (a) {
this.push(JSON.stringify(a))
}
while (left < right) { //注意条件两次最多两人
if (people[left] + people[right] <= limit) {
//装上left, right
track.add([people[left], people[right]])
left++;
right--
boats++;
} else {
//只能装right
track.add([people[right]])
boats++
right--
}
if (right == left) {
track.add([people[right]])
//只能装left
boats++;
}
}
console.log(track, 'only test, limit = ', limit)
return boats;
};
//1,2,2, 3
numRescueBoats([3, 2, 2, 1], 3)
numRescueBoats([3, 5, 3, 4], 5)
numRescueBoats([1, 1, 2, 4], 4)
原文地址:https://www.cnblogs.com/rubylouvre/p/12147761.html
时间: 2024-11-06 11:30:03