本文共 1212 字,大约阅读时间需要 4 分钟。
题目:
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 = 3Output: 1Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3Output: 3Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5Output: 4Explanation: 4 boats (3), (3), (4), (5)
Note:
1 <= people.length <= 50000
1 <= people[i] <= limit <= 30000
思路:
首先应该很自然想到sort,因为本质是找小于limit的两点,从小到大排列显然更容易解题。其次还是因为找两点,那么用two pointer遍历vector。明确以下几点:左瘦,右胖,如果左加右大于limit,那么我们右指针向左移,但是左指针不动(题目明确给出一船必能装一人,因此无论如何右边的人肯定能被装);否则就左边和右边一起装,左指针向右,右指针向左。综上,可以看出在遍历中,每一轮无论如何,右指针必向左,并且所需要的船数量必加一。最后思考一下就边界条件,如果左右指针同时指向同一个人,那么无论如何船肯定会加一,并且也只需要加一,因为这是剩下的最后一个人,所以遍历的while条件应该为l<=r。
代码:
class Solution {
public: int numRescueBoats(vector<int>& people, int limit) { sort(people.begin(),people.end()); int ans=0; int l=0, r=people.size()-1; while(l<=r) { if(people[l]+people[r]<=limit) l++; r--; ans++; } return ans; } };转载地址:http://aaqo.baihongyu.com/