575 Distribute Candies 分發糖果問題

給定一個整數數組這個數組的長度爲偶數,不同的數字代表不同的種類糖果。每一個數字意味着一個糖果。你需要把這些糖果等量的分發給弟弟妹妹。返回的最大種類數量糖果妹妹可以獲得。


example1

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. 


example2

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. 


solution

public class Solution {
    public int distributeCandies(int[] candies) {
        HashSet < Integer > set = new HashSet < > ();
        for (int candy: candies) {
            set.add(candy);
        }
        return Math.min(set.size(), candies.length / 2);
    }
}

不同種類的數量大於一半,就得到一半的糖果數量,若小於一半,則爲全部的種類量。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章