Leetcode 881 救生艇 双指针

 

  JAVA:

    public final int numRescueBoats(int[] people, int limit) {
        if (people == null || people.length == 0) return 0;
        Arrays.sort(people);
        int len = people.length, begin = 0, end = len - 1, re = 0;
        while (begin <= end) {
            if (people[end] + people[begin] <= limit) begin++;
            end--;
            re++;
        }
        return re;
    }

  JS:

var numRescueBoats = function (people, limit) {
    if (!people || !people.length) return 0;
    let len = people.length, begin = 0, end = len - 1, re = 0;
    people.sort(function (a, b) {
        return a - b
    });
    while (begin <= end) {
        if (people[end] + people[begin] <= limit) begin++;
        end--;
        re++
    }
    return re;
};

 

posted @ 2021-04-18 14:37  牛有肉  阅读(59)  评论(0编辑  收藏  举报