标签:get 一个 sam mos input 实现 save cno sum
The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.)
Example 1:
Input: people = [1,2], limit = 3 Output: 1 Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3 Output: 3 Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5 Output: 4 Explanation: 4 boats (3), (3), (4), (5)
Note:
1 <= people.length <= 500001 <= people[i] <= limit <= 30000救生艇。题意是给一些人的体重和一个船的最大载重量limit,请问最多需要几条船才能装下所有人,每条船最多装两个人。
思路是贪心。这里贪心贪的是一条船能否在已经装了一个很重的人的情况下还能再装一个比较轻的人。所以需要先对input排序,然后用双指针逼近的方法做。
时间O(nlogn)
空间O(1)
Java实现
1 class Solution { 2 public int numRescueBoats(int[] people, int limit) { 3 Arrays.sort(people); 4 int i = 0; 5 int j = people.length - 1; 6 int res = 0; 7 while (i <= j) { 8 res++; 9 if (people[i] + people[j] <= limit) { 10 i++; 11 } 12 j--; 13 } 14 return res; 15 } 16 }
[LeetCode] 881. Boats to Save People
标签:get 一个 sam mos input 实现 save cno sum
原文地址:https://www.cnblogs.com/cnoodle/p/13070394.html