原題連接在這裏:https://leetcode.com/problems/boats-to-save-people/ide
題目:spa
The i
-th person has weight people[i]
, and each boat can carry a maximum weight of limit
.code
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit
.blog
Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.)leetcode
Example 1:get
Input: people = [1,2], limit = 3 Output: 1 Explanation: 1 boat (1, 2)
Example 2:input
Input: people = [3,2,2,1], limit = 3 Output: 3 Explanation: 3 boats (1, 2), (2) and (3)
Example 3:it
Input: people = [3,5,3,4], limit = 5 Output: 4 Explanation: 4 boats (3), (3), (4), (5)
Note:io
1 <= people.length <= 50000
1 <= people[i] <= limit <= 30000
題解:class
When trying to find out minimum num ber of boats to carry every given person, it is best to sort array first and let heaviest person and lightest person fit the boat first.
If it is overweight, then only let the heaviest person take and boat, res++.
Otherwise, let both of them take the boat, and since boat could carry at most 2 people at the same time, move both pointers, res++.
Time Complexity: O(nlogn). n = people.length.
Space: O(1).
AC Java:
1 class Solution { 2 public int numRescueBoats(int[] people, int limit) { 3 if(people == null || people.length == 0){ 4 return 0; 5 } 6 7 Arrays.sort(people); 8 int res = 0; 9 int i = 0; 10 int j = people.length-1; 11 while(i<=j){ 12 if(people[i]+people[j]<=limit){ 13 i++; 14 j--; 15 }else{ 16 j--; 17 } 18 19 res++; 20 } 21 22 return res; 23 } 24 }