先对数组排序,判断最大的+最小的是否小于等于目标数,如果成立则左右指针都移动,count +1;如果不成立,则最大数必定是单独一座船,右指针移动,count+1;最后判断指针是否重叠,重叠则剩下一个单独的人,count+1,否则已经载完人;

    1. /**
    2. * @param {number[]} people
    3. * @param {number} limit
    4. * @return {number}
    5. */
    6. var numRescueBoats = function(people, limit) {
    7. if(!people.length) return 0
    8. if(people.length === 1) return 1
    9. people.sort((a, b) => a - b)
    10. let start = 0,
    11. end = people.length - 1,
    12. count = 0
    13. while(start < end) {
    14. if(people[start] + people[end] <= limit) {
    15. start++
    16. }
    17. count++
    18. end--
    19. }
    20. return start === end ? ++count : count
    21. };