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

你可能感兴趣的文章
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>
mysqldump备份时忽略某些表
查看>>
mysqldump实现数据备份及灾难恢复
查看>>
mysqldump数据库备份无法进行操作只能查询 --single-transaction
查看>>