LeetCode之Distribute Candies

题目概述:

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

思路:

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

示例:

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. 

代码:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值