[LeetCode] Distribute Candies 分糖果


 

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

Example 1:

Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. 
The sister has three different kinds of candies. 

 

Example 2:

Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. 
The sister has two different kinds of candies, the brother has only one kind of candies. 

 

Note:

  1. The length of the given array is in range [2, 10,000], and will be even.
  2. The number in given array is in range [-100,000, 100,000].

 

這道題給我們一堆糖,每種糖的個數不定,分給兩個人,讓我們求其中一個人能拿到的最大的糖的種類數。那么我們想,如果總共有n個糖,平均分給兩個人,每人得到n/2塊糖,那么能拿到的最大的糖的種類數也就是n/2種,不可能再多,只可能再少。那么我們要做的就是統計出總共的糖的種類數,如果糖的種類數小於n/2,說明拿不到n/2種糖,最多能拿到的種類數數就是當前糖的總種類數,明白了這點就很容易了,我們利用集合set的自動去重復特性來求出糖的種類數,然后跟n/2比較,取二者之中的較小值返回即可,參加代碼如下:

 

解法一:

class Solution {
public:
    int distributeCandies(vector<int>& candies) {
        unordered_set<int> s;
        for (int candy : candies) s.insert(candy);
        return min(s.size(), candies.size() / 2);
    }
};

 

下面這種方法叼的不行,直接用把上面的解法濃縮為了一行,有種顯擺的感覺:

 

解法二:

class Solution {
public:
    int distributeCandies(vector<int>& candies) {
        return min(unordered_set<int>(candies.begin(), candies.end()).size(), candies.size() / 2);
    }
};

 

參考資料:

https://leetcode.com/problems/distribute-candies/

https://leetcode.com/problems/distribute-candies/discuss/102946/c-1-liner

https://leetcode.com/problems/distribute-candies/discuss/102939/java-8-one-line-solution-on

https://leetcode.com/problems/distribute-candies/discuss/102879/java-solution-3-lines-hashset

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM