Leetcode: 【每日一题】- 2019-10-24 - 881. 救生艇

Created on 24 Oct 2019  ·  3Comments  ·  Source: azl397985856/leetcode

第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。

每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。

返回载到每一个人所需的最小船数。(保证每个人都能被船载)。

 

示例 1:

输入:people = [1,2], limit = 3
输出:1
解释:1 艘船载 (1, 2)
示例 2:

输入:people = [3,2,2,1], limit = 3
输出:3
解释:3 艘船分别载 (1, 2), (2) 和 (3)
示例 3:

输入:people = [3,5,3,4], limit = 5
输出:4
解释:4 艘船分别载 (3), (3), (4), (5)
提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/boats-to-save-people
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Array DFS Daily Question LeetCode Medium

Most helpful comment

领取

class Solution {
public:
    int numRescueBoats(vector<int>& p, int limit) {
        int cnt = 0;
        sort(p.begin(),p.end());
        int l = 0,r = p.size()-1;
        while(l<=r){
            if(p[l]+p[r]>limit) r--;
            else l++,r--;
            cnt++;
        }
        return cnt;
    }
};

image

All 3 comments

领取

class Solution {
public:
    int numRescueBoats(vector<int>& p, int limit) {
        int cnt = 0;
        sort(p.begin(),p.end());
        int l = 0,r = p.size()-1;
        while(l<=r){
            if(p[l]+p[r]>limit) r--;
            else l++,r--;
            cnt++;
        }
        return cnt;
    }
};

image

Python Solution With two-pointer:

since the problem notes that Each boat carries at most 2 people at the same time', so we could solve it with two-pointer. If Not, maybe we should solve it with something like dfs

basic:

  • sort people (ascending assumed)
  • setup two pointer left and right
  • if the people[left] + people[right] greater than limit, carry the people[right]
  • else carry both of them
  • note that, if l equal r , mean we should carry him with a single boat

code as below:

def numRescueBoats(self, people: List[int], limit: int) -> int:
        res = 0
        l = 0
        r = len(people) - 1
        people.sort()

        while l < r:
            total = people[l] + people[r]
            if total > limit:
                r -= 1
                res += 1
            else:
                r -= 1
                l += 1
                res += 1
        if (l == r):
            return res + 1
        return res

@maninbule done (Life is like a Boat )

Was this page helpful?
0 / 5 - 0 ratings