Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。
医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。
给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的最多种类数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/distribute-candies
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public static int distributeCandies(int[] candyType) {
HashMap hashMap = new HashMap<>();
if (candyType.length==0){
return 0;
}
int res = candyType.length/2;
hashMap.put(candyType[0],1);
for (int i = 1; i < candyType.length ; i++) {
if (hashMap.containsKey(candyType[i])){
int tmp = hashMap.get(candyType[i])+1;
hashMap.put(candyType[i],tmp);
}else {
hashMap.put(candyType[i],1);
}
}
int typenu = 0;
for (int nu:hashMap.keySet()) {
typenu++;
}
if (typenu>=res){
return res;
}else {
return typenu;
}
}
心得:对于我来说 这个太拉跨了 快找找资料 找相对应的其他方法
用到的知识点: Java hashmap循环的遍历
相关遍历方法有 4种
第一种:
for(String key:map.keySet()) {
System.out.println("Key:"+key+" value:"+map.get(key));
}
第二种:
Iterator ite = map.entrySet().iterator();
while(ite.hasNext()) {
Map.Entry entry = (Map.Entry)ite.next();
System.out.println("Key:"+entry.getKey()+" value:"+entry.getValue());
}
第三种
for(Entryentry : map.entrySet()) { System.out.println("Key:"+entry.getKey()+" value:"+entry.getValue()); }
第四种
for(相关类型 (int float double )…… :map.values()) {
System.out.println((int)……);
}
hashmap 的大小的取值 hashmap.size();
直接使用hashset 进行 去重
再求值
public int distributeCandies(int[] candyType) {
HashSet < Integer > set = new HashSet < > ();
for (int i = 0; i < candyType.length; i++) {
set.add(candyType[i]);
}
if (set.size()>(candyType.length/2)){
return (candyType.length)/2;
}else {
return set.size();
}
}



