[LeetCode] 881. Boats to Save People 渡人的船



The i-th person has weight people[i], and each boat can carry a maximum weight of limit.html

Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.git

Return the minimum number of boats to carry every given person.  (It is guaranteed each person can be carried by a boat.)github

Example 1:算法

Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)

Example 2:ide

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:code

  • 1 <= people.length <= 50000
  • 1 <= people[i] <= limit <= 30000



這道題讓咱們載人過河,說是每一個人的體重不一樣,每條船承重有個限度 limit(限定了這個載重大於等於最重人的體重),同時要求每條船不能超過兩人,這尼瑪是獨木舟吧,也就比 kayak 大一點點吧(不過也有多是公園湖中的雙人腳蹬船,懷念小時候在公園划船的日子~),問咱們將全部人載到對岸最少須要多少條船。從題目中的例子2能夠看出,最肥的人有可能一人佔一條船,固然若是船的載量夠大的話,可能還能擠上一個瘦子,那麼最瘦的人是最可能擠上去的,因此策略就是胖子加瘦子的上船組合。那麼這就是典型的貪婪算法的適用場景啊,首先要給全部人按體重排個序,從瘦子到胖子,這樣咱們才能快速的知道當前最重和最輕的人。而後使用雙指針,left 指向最瘦的人,right 指向最胖的人,當 left 小於等於 right 的時候,進行 while 循環。在循環中,胖子是必定要上船的,因此 right 自減1是確定有的,可是仍是要看可否再帶上一個瘦子,能的話 left 自增1。而後結果 res 必定要自增1,由於每次都要用一條船,參見代碼以下:htm


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 同步地址:blog

https://github.com/grandyang/leetcode/issues/881leetcode



參考資料:

https://leetcode.com/problems/boats-to-save-people/

https://leetcode.com/problems/boats-to-save-people/discuss/156740/C%2B%2BJavaPython-Two-Pointers

https://leetcode.com/problems/boats-to-save-people/discuss/156855/6-lines-Java-O(nlogn)-code-sorting-%2B-greedy-with-greedy-algorithm-proof.



LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索