classSolution { public: intnumRescueBoats(vector<int>& people, int limit){ sort(people.begin(), people.end()); int ans = 0; for (int l = 0, r = people.size() - 1; l <= r; ans++, r--) { // 不用特判l是否等于r,因为不影响结果(若l=r则说明就剩一个人了,带不带那个“虚空影子”都无所谓) if (people[l] + people[r] <= limit) { l++; } } return ans; } };
CPP
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// package main
// import "sort"
funcnumRescueBoats(people []int, limit int)int { sort.Ints(people); ans := 0 for l, r := 0, len(people) - 1; l <= r; ans, r = ans + 1, r - 1 { if people[l] + people[r] <= limit { l++; } } return ans }
GO
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// import java.util.Arrays;
classSolution { publicintnumRescueBoats(int[] people, int limit) { Arrays.sort(people); intans=0; for (intl=0, r = people.length - 1; l <= r; ans++, r--) { if (people[l] + people[r] <= limit) { l++; } } return ans; } }
JAVA
Python
1 2 3 4 5 6 7 8 9 10 11 12 13
# from typing import List
classSolution: defnumRescueBoats(self, people: List[int], limit: int) -> int: people.sort() ans = 0 l, r = 0, len(people) - 1 while l <= r: if people[l] + people[r] <= limit: l += 1 r -= 1 ans += 1 return ans