Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

Code shrimp is a sand carving and funny boy who likes listening to music, playing games and writing as well as most of his friends. The days are still very long, let’s refuel our efforts together 🌈



✨ topic


  1. Sort an array

  2. Greed + double pointer


🌈 Case Explanation

Take case 3 for example

Sort the array by:3, 5-tetrafluorobenzoic.limit = 5

Maintaining dual PointersLeft = 0, right = people. Length - 1

Cyclic conditions:left <= rightBecause, whenleft == rightWhen, there was still one person who needed to make the boat, so it could not be usedleft < right


Case 3 might not be obvious, so let’s do case 2 again

Sort the array by:1,2,2,3.limit = 3

Why is it left++, because they say a boat can’t do more than two people


🔥 code implementation

class Solution {
    public int numRescueBoats(int[] people, int limit) {
    
        Arrays.sort(people);
        int len = people.length;
        int left = 0, right = len - 1;

        int res = 0;

        while (left <= right) {
        	// If people[left] + people[right] <= limit, leave ++
        	// It is greedy to make the boat as crowded as possible
            if (people[left] + people[right] <= limit) {
                ++left;
            }
            --right;
            ++res;
        }
        returnres; }}Copy the code

💖 finally

I am aCode pipi shrimp, a prawns lover who loves to share knowledge, will update useful blog posts in the future, looking forward to your attention!!

Creation is not easy, if this blog is helpful to you, I hope you can == one key three even oh! Thank you for your support. See you next time