博客
关于我
881. Boats to Save People
阅读量:288 次
发布时间:2019-03-01

本文共 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/

你可能感兴趣的文章
MSB与LSB
查看>>
MSCRM调用外部JS文件
查看>>
MSCRM调用外部JS文件
查看>>
MSEdgeDriver (Chromium) 不适用于版本 >= 79.0.313 (Canary)
查看>>
MsEdgeTTS开源项目使用教程
查看>>
msf
查看>>
MSSQL数据库查询优化(一)
查看>>
MSSQL数据库迁移到Oracle(二)
查看>>
MSSQL日期格式转换函数(使用CONVERT)
查看>>
MSTP多生成树协议(第二课)
查看>>
MSTP是什么?有哪些专有名词?
查看>>
Mstsc 远程桌面链接 And 网络映射
查看>>
Myeclipse常用快捷键
查看>>
MyEclipse更改项目名web发布名字不改问题
查看>>
MyEclipse用(JDBC)连接SQL出现的问题~
查看>>
mt-datetime-picker type="date" 时间格式 bug
查看>>
myeclipse的新建severlet不见解决方法
查看>>
MyEclipse设置当前行背景颜色、选中单词前景色、背景色
查看>>
Mtab书签导航程序 LinkStore/getIcon SQL注入漏洞复现
查看>>
myeclipse配置springmvc教程
查看>>