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 <= 50000
1 <= people[i] <= limit <= 30000
這道題讓我們載人過河,說是每個人的體重不同,每條船承重有個限度 limit(限定了這個載重大於等於最重人的體重),同時要求每條船不能超過兩人,這尼瑪是獨木舟吧,也就比 kayak 大一點點吧(不過也有可能是公園湖中的雙人腳蹬船,懷念小時候在公園划船的日子~),問我們將所有人載到對岸最少需要多少條船。從題目中的例子2可以看出,最肥的人有可能一人占一條船,當然如果船的載量夠大的話,可能還能擠上一個瘦子,那么最瘦的人是最可能擠上去的,所以策略就是胖子加瘦子的上船組合。那么這就是典型的貪婪算法的適用場景啊,首先要給所有人按體重排個序,從瘦子到胖子,這樣我們才能快速的知道當前最重和最輕的人。然后使用雙指針,left 指向最瘦的人,right 指向最胖的人,當 left 小於等於 right 的時候,進行 while 循環。在循環中,胖子是一定要上船的,所以 right 自減1是肯定有的,但是還是要看能否再帶上一個瘦子,能的話 left 自增1。然后結果 res 一定要自增1,因為每次都要用一條船,參見代碼如下:
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
int res = 0, n = people.size(), left = 0, right = n - 1;
sort(people.begin(), people.end());
while (left <= right) {
if (people[left] + people[right] <= limit) ++left;
--right;
++res;
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/881
參考資料:
https://leetcode.com/problems/boats-to-save-people/
https://leetcode.com/problems/boats-to-save-people/discuss/156740/C%2B%2BJavaPython-Two-Pointers
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)