这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战
题目
Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。
医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。
给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的最多种类数。
示例
输入: candyType = [1,1,2,2,3,3]
输出: 3
解释: Alice 只能吃 6 / 2 = 3 枚糖,由于只有 3 种糖,她可以每种吃一枚。
输入:candyType = [1,1,2,3]
输出:2
解释:Alice 只能吃 4 / 2 = 2 枚糖,不管她选择吃的种类是 [1,2]、[1,3] 还是 [2,3],她只能吃到两种不同类的糖。
输入: candyType = [6,6,6,6]
输出: 1
解释: Alice 只能吃 4 / 2 = 2 枚糖,尽管她能吃 2 枚,但只能吃到 1 种糖。
提示
n == candyType.length2 <= n <= 10^4n是一个偶数-10^5 <= candyType[i] <= 10^5
解题思路
贪心
要求尽可能多的糖果种类,这种题目一般都是会选择使用贪心算法来解题,毕竟可以多吃点嘛~
- 首先,医生建议Alice最多只能吃所有糖的
n / 2,那么我们可以得到最大值为n / 2。 - 我们需要知道
candyType数组中一共有多少种糖果,这里可以采用哈希来统计,求的种类m。 - 得到最大值与糖果类型之后,因为答案不会超过
n / 2, 且种类不会超过m,那么我们只需要求出两者的最小值即可得出最终结果。
class Solution {
public int distributeCandies(int[] candyType) {
// 得到最大值
int n = candyType.length / 2;
// 统计糖果种类
Set<Integer> set = new HashSet<>();
for(int candy : candyType){
set.add(candy);
// 大于等于最大值即可退出循环
if(set.size() >= n){
break;
}
}
// 返回两者的最小值
return Math.min(set.size(), n);
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度:
数组优化
对于数据范围明确的,我们可以采用一个布尔数组来进行优化。
class Solution {
public int distributeCandies(int[] candyType) {
int n = candyType.length / 2;
int count = 0;
boolean[] candys = new boolean[100000 * 2 + 1];
for(int candy : candyType){
// 遍历candyType数组,只有当前元素没统计过,才进行统计
if(!candys[candy + 100000]){
++count;
candys[candy + 100000] = true;
}
}
// 获得最小值并返回
return Math.min(count, n);
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度:
最后
文章有写的不好的地方,请大佬们不吝赐教,错误是最能让人成长的,愿我与大佬间的距离逐渐缩短!
如果觉得文章对你有帮助,请 点赞、收藏、关注、评论 一键四连支持,你的支持就是我创作最大的动力!!!
题目出处: