• LeetCode 881. Boats to Save People


    原题链接在这里:https://leetcode.com/problems/boats-to-save-people/

    题目:

    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 = 3
    Output: 1
    Explanation: 1 boat (1, 2)
    

    Example 2:

    Input: people = [3,2,2,1], limit = 3
    Output: 3
    Explanation: 3 boats (1, 2), (2) and (3)
    

    Example 3:

    Input: people = [3,5,3,4], limit = 5
    Output: 4
    Explanation: 4 boats (3), (3), (4), (5)

    Note:

    • 1 <= people.length <= 50000
    • 1 <= people[i] <= limit <= 30000


    题解:

    When trying to find out minimum num ber of boats to carry every given person, it is best to sort array first and let heaviest person and lightest person fit the boat first.

    If it is overweight, then only let the heaviest person take and boat, res++.

    Otherwise, let both of them take the boat, and since boat could carry at most 2 people at the same time, move both pointers, res++.

    Time Complexity: O(nlogn). n = people.length.

    Space: O(1).

    AC Java: 

     1 class Solution {
     2     public int numRescueBoats(int[] people, int limit) {
     3         if(people == null || people.length == 0){
     4             return 0;
     5         }
     6         
     7         Arrays.sort(people);
     8         int res = 0;
     9         int i = 0; 
    10         int j = people.length-1;
    11         while(i<=j){
    12             if(people[i]+people[j]<=limit){
    13                 i++;
    14                 j--;
    15             }else{
    16                 j--;
    17             }
    18             
    19             res++;
    20         }
    21         
    22         return res;
    23     }
    24 }
  • 相关阅读:
    Windows 8将替换Win32 API
    密码强度检测:passwordStrength
    整数溢出与程序安全
    编程经验谈:如何正确使用内存
    C/C++指针学习的两个经典实例
    VC调试入门
    一些电子书籍的网站
    BMP文件格式分析(zz)
    C/C++ 跨平台I/O操作技巧
    Windows下C语言网络编程快速入门
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11421611.html
Copyright © 2020-2023  润新知