先对数组排序,判断最大的+最小的是否小于等于目标数,如果成立则左右指针都移动,count +1;如果不成立,则最大数必定是单独一座船,右指针移动,count+1;最后判断指针是否重叠,重叠则剩下一个单独的人,count+1,否则已经载完人;
/**
* @param {number[]} people
* @param {number} limit
* @return {number}
*/
var numRescueBoats = function(people, limit) {
if(!people.length) return 0
if(people.length === 1) return 1
people.sort((a, b) => a - b)
let start = 0,
end = people.length - 1,
count = 0
while(start < end) {
if(people[start] + people[end] <= limit) {
start++
}
count++
end--
}
return start === end ? ++count : count
};