博客
关于我
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中B+Tree索引原理
查看>>
mysql中cast() 和convert()的用法讲解
查看>>
mysql中datetime与timestamp类型有什么区别
查看>>
MySQL中DQL语言的执行顺序
查看>>
mysql中floor函数的作用是什么?
查看>>
MySQL中group by 与 order by 一起使用排序问题
查看>>
mysql中having的用法
查看>>
MySQL中interactive_timeout和wait_timeout的区别
查看>>
mysql中int、bigint、smallint 和 tinyint的区别、char和varchar的区别详细介绍
查看>>
mysql中json_extract的使用方法
查看>>
mysql中json_extract的使用方法
查看>>
mysql中kill掉所有锁表的进程
查看>>
mysql中like % %模糊查询
查看>>
MySql中mvcc学习记录
查看>>
mysql中null和空字符串的区别与问题!
查看>>