?LeetCode刷題實戰(zhàn)575:分糖果
Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.
The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.
Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.
示例? ? ? ? ? ? ? ? ? ? ? ? ?
示例 1:
輸入:candyType = [1,1,2,2,3,3]
輸出:3
解釋:Alice 只能吃 6 / 2 = 3 枚糖,由于只有 3 種糖,她可以每種吃一枚。
示例 2:
輸入:candyType = [1,1,2,3]
輸出:2
解釋:Alice 只能吃 4 / 2 = 2 枚糖,不管她選擇吃的種類是 [1,2]、[1,3] 還是 [2,3],她只能吃到兩種不同類的糖。
示例 3:
輸入:candyType = [6,6,6,6]
輸出:1
解釋:Alice 只能吃 4 / 2 = 2 枚糖,盡管她能吃 2 枚,但只能吃到 1 種糖。
解題
class?Solution?{
public:
????int?distributeCandies(vector<int>& candies)?{
????????unordered_set<int> st;
????????//統(tǒng)計總共的糖果的種類
????????for(int& num:candies){
????????????if(st.count(num)==0){
????????????????st.insert(num);
????????????}
????????}
????????//根據(jù)種類是否超過了總的數(shù)量的一半,來判斷返回值
????????return?st.size()<=(candies.size()/2)?st.size():candies.size()/2;
????}
};
