575. Distribute Candies

本文探讨了LeetCode上的一道关于糖果分配的问题,旨在将不同种类的糖果平均分成两份,求解其中一份能包含的最大种类数量。文章提供了三种解决方法:排序后计数不同元素、去除重复元素后比较集合大小、使用unordered_set快速统计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述【Leetcode

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:
The length of the given array is in range [2, 10,000], and will be even.
The number in given array is in range [-100,000, 100,000].

这道题就是把数组平均分为两组,其中一组包含种类最多,求该种类个数

方法一:
就是先排好序,然后就找不同的数字即可

class Solution {
public:
    int distributeCandies(vector<int>& candies) {
        int n = candies.size();
        if(n == 0) return 0;
       sort(candies.begin(),candies.end());
       int count = 1;
       int temp = candies[0];
        for(int i = 1; i < n; i++ ){
            if(candies[i] != candies[i-1] && count < n/2)count++;
        }
        return count;
    }
};

方法二:删除重复项之后大小与之前数组作比较:

class Solution {
public:
    int distributeCandies(vector<int>& candies) {
        int n = candies.size();
        if(n == 0) return 0;
        sort(candies.begin(),candies.end());
        candies.erase(unique(candies.begin(),candies.end()),candies.end());
        int t = candies.size();
        if(t >= n/2) return n/2;
        if(t  < n/2) return t;
    }
};

方法三:用unordered_set,类似于方法二,但是运行更快:

class Solution {
public:
    int distributeCandies(vector<int>& candies) {
        int n = candies.size();
        unordered_set<int> s(candies.begin(), candies.end());
        if (s.size() >= n/2) return n/2;
        else return s.size();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值