《LeetCode之每日一题》:196.分糖果

分糖果


题目链接: 分糖果

有关题目

给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。
你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。
示例 1:

输入: candies = [1,1,2,2,3,3]
输出: 3
解析: 一共有三种种类的糖果,每一种都有两个。
     最优分配方案:妹妹获得[1,2,3],弟弟也获得[1,2,3]。这样使妹妹获得糖果的种类数最多。
示例 2 :

输入: candies = [1,1,2,3]
输出: 2
解析: 妹妹获得糖果[2,3],弟弟获得糖果[1,1],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。
注意:

数组的长度为[2, 10,000],并且确定为偶数。
数组中数字的大小在范围[-100,000, 100,000]内。

题解

法一:暴力
思路:

小女孩能得到的最大糖果的种类数为 n / 2,当糖果的种类数m 小于 n / 2时,则
小女孩能得到的最大糖果的种类数为 m。
故我们可以统计candyType中的种类数,candyType数组中重复出现的数字我们标记一下
最后结果在candyType.size() 与 cnt之间选择
class Solution {
public:
    int distributeCandies(vector<int>& candyType) {
        int n = candyType.size();
        int cnt = 0;
        for (int i = 0;i < n && cnt < n / 2; i++)
        {
            if (candyType[i] != INT_MIN)
            {
                cnt++;
                for (int j = i + 1; j < n; j++)
                {
                    if (candyType[i] == candyType[j])
                        candyType[j] = INT_MIN;
                }
            }
        }

        return cnt;
    }
};

在这里插入图片描述
法二:排序
参考官方题解

class Solution {
public:
    int distributeCandies(vector<int>& candyType) {
        int n = candyType.size();
        int cnt = 1;

        sort(candyType.begin(), candyType.end());
        for (int i = 1; i < n && cnt < n / 2; i++)
        {
            if (candyType[i] > candyType[i - 1])
                cnt++;
        }

        return cnt;
    }
};

在这里插入图片描述

法三:分类讨论 + 贪心

代码一:
参考官方题解

class Solution {
public:
    int distributeCandies(vector<int>& candyType) {
        unordered_set<int> set(candyType.begin(), candyType.end());
        return min(set.size(), candyType.size() / 2);
    }
};

在这里插入图片描述
代码二:

class Solution {
public:
    int distributeCandies(vector<int>& candyType) {
        unordered_set<int> set;
        for (auto &x : candyType)
            set.insert(x);
        
        return min(set.size(), candyType.size() / 2);
    }
};

在这里插入图片描述

代码三:
参考官方题解评论区下梦璃夜·天星

class Solution {
public:
    int distributeCandies(vector<int>& candyType) {
        bitset<200001> s;//二进制的数组,可以直接用01串赋值
        for (auto &x : candyType)
            if (!s[x + 1e5])
                s.set(x + 1e5);
        
        return min(candyType.size() / 2, s.count());
    }
};

时间复杂度:O(n),n为candyType的大小
空间复杂度:O©,C为二进制数组的大小

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值