题目
Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。
医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。
给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的 最多 种类数。
思路
需要找到吃到糖的最多种类数,有两种情况
- n/2 即最多的种类数
- 种类最多页不超过 n/2
获取结果需要知道糖果最多的种类数量, 那么就需要遍历数组, 如果达到 n/2 个种类糖果就结束遍历
使用 Set 来存储种类, 如果添加成功则表示这是新的种类
代码
class Solution {
public int distributeCandies(int[] candyType) {
int n = candyType.length;
int maxType = n / 2;
Set<Integer> set = new HashSet<>();
int count = 0;
for (int i : candyType) {
boolean add = set.add(i);
if (add) {
count++;
}
if (count == maxType) {
break;
}
}
return count;
}
}
题解
三叶姐题解: leetcode.cn/problems/di…
看了题解之后感觉自己没必要定义 count 变量了.. 直接取 set 的长度就可以了...