LeetCode之Distribute Candies

来源:互联网 发布:java项目有红色感叹号 编辑:程序博客网 时间:2024/05/22 12:40

题目概述:

给一个偶数个数的整数数组,数组里相同的数代表同一种糖果,不同的数代表不同种类的糖果,把这些糖果平均分给弟弟和姐姐,返回姐姐可能得到的最多的糖果种类的个数。

思路:

如果糖果的种类数小于数组的一半,返回种类数,否则,返回数组的一半值。

示例:

Example 1:Input: candies = [1,1,2,2,3,3]Output: 3Explanation: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: 2Explanation: 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. 

代码:

class Solution {public:    int distributeCandies(vector<int>& candies) {        //candies呈升序排列        sort(candies.begin(),candies.end());        //candies数组的长度        int length=candies.size();        //candies的种类数        int num=1;        for(int i=1;i<length;i++)        {            if(candies[i]!=candies[i-1])            {                num++;            }        }        if(num>=length/2)            return length/2;        else            return num;    }};

另一种解法:

class Solution {public:    int distributeCandies(vector<int>& candies) {        unordered_set<int> kinds;        for (int kind : candies) {            kinds.insert(kind);        }        return min(kinds.size(), candies.size() / 2);    }};
set集合是无序集合容器。




0 0