目标
Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。
医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。
给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的 最多 种类数。
示例 1:
输入:candyType = [1,1,2,2,3,3]
输出:3
解释:Alice 只能吃 6 / 2 = 3 枚糖,由于只有 3 种糖,她可以每种吃一枚。
示例 2:
输入:candyType = [1,1,2,3]
输出:2
解释:Alice 只能吃 4 / 2 = 2 枚糖,不管她选择吃的种类是 [1,2]、[1,3] 还是 [2,3],她只能吃到两种不同类的糖。
示例 3:
输入:candyType = [6,6,6,6]
输出:1
解释:Alice 只能吃 4 / 2 = 2 枚糖,尽管她能吃 2 枚,但只能吃到 1 种糖。
说明:
- n == candyType.length
- 2 <= n <= 10^4
- n 是一个偶数
- -10^5 <= candyType[i] <= 10^5
思路
统计糖果种类,然后与n/2比较,取其中的最小值。
可以使用 HashSet
来计算种类数量,题解中最快的解法是自定义了hash函数,将种类映射到数组下标,通过判断相应位置上的值来计数。
代码
/**
* @date 2024-06-02 9:26
*/
public class DistributeCandies575 {
public int distributeCandies(int[] candyType) {
int n = candyType.length;
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
set.add(candyType[i]);
}
return Math.min(set.size(), n / 2);
}
public int distributeCandies_v1(int[] candyType) {
int res = 0;
int n = candyType.length;
byte[] mask = new byte[200001];
for (int i = 0; i < n; i++) {
int c = candyType[i];
// 由于类型可能为负数,所以使用c+100000
if (mask[c + 100000] == 0) {
mask[c + 100000] = 1;
res++;
if (res > n / 2) return n / 2;
}
}
return res;
}
}