This is the 30th day of my participation in the August Challenge


Related articles

LeetCode brush questions summary: LeetCode brush questions

1. Title Description


Points of candy

Given an even-length array in which different numbers represent different types of candy, each number represents a candy. You need to divide the candy equally between one brother and one sister. Returns the maximum number of types of candy your sister can get.

Start with simple questions to brush, exercise their thinking ability, for the interview preparation ~

Second, train of thought analysis


  • Look at the examples in the title, let’s clarify the idea ~

  • Example 1:

    [1,1,2,2,3] there are two of each kind of candies Optimal allocation: younger sister gets [1,2,3], younger brother also gets [1,2,3]. This gives her the most variety of sweets.Copy the code
  • Example 2:

    Sister has two different kinds of candies, the brother has only one This maximizes the number of sweets available to the younger sister.Copy the code
  • First determine the meaning of the topic.

  • The number of sweets must be even.

  • But the type of candy varies, maybe there are two ones, a two, and a three.

  • In this case, you definitely want to give your sister two kinds of candy, because your sister needs the largest variety of candy.

  • After the pit is finished, you can think of a way to write.

  • How do I find unique elements?

  • The set!!!!!! We can use set to determine all unique elements.

  • Finally, the set size is the number of candy types.

  • The value to be returned is again given by min(count,n/2).

  • Min (count,n/2) The smallest number in a given number. If any of the arguments cannot be converted to a numeric value, NaN is returned.

AC code


  • Set cracking method:

    class Solution { public int distributeCandies(int[] candyType) { HashSet < Integer > set = new HashSet < > (); for (int candy: candyType) { set.add(candy); } return Math.min(set.size(), candyType.length / 2); }}Copy the code
    • It’s very efficient

Four,

  • Thousands of ideas to solve the problem, whether this method is good, or whimsical solution, can solve is a good way! White cat black cat can catch mice cat is a good cat!
  • Here are a few other LeetCode solutions for reference!
  • Click to jump: official solution
  • Click to jump to: Solution 2

The road ahead is long, I see no end, I will search high and low

If you think I bloggers write well! Writing is not easy, please like, follow, comment and give encouragement to the blogger ~ Hahah