贪心算法

救生艇

2025-09-28  本文已影响0人  何以解君愁

救生艇

class Solution {
    public int numRescueBoats(int[] people, int limit) {
        Arrays.sort(people);
        int res = 0;
        int left = 0,right = people.length - 1;

        while(left <= right){
            if(left == right){
                res++;
                break;
            }

            if(people[left] + people[right] <= limit){
                res++;
                left++;
                right--;
            }else{
                res++;
                right--;
            }
        }
        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读