博客
关于我
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/

你可能感兴趣的文章
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>