问题:Leetcode 575-分发糖果
问题链接: https : //leetcode.com/problems/distribute-candies/
简单描述:给定一个描述一袋糖果的数组,找出如果糖果平均分配可以得到的唯一糖果类型的最大数量。
因此,对于等分布后的数组[1,1,2,2,3,3]
,每个组应获得3个糖果,并且可以给出的唯一糖果的最大数量也为3,即[1,2,3]
。
Java解决方案:
class Solution {
public int distributeCandies ( int [] candies ) {
Set < Integer > set = new HashSet <>();
for ( int candy : candies ) {
set . add ( candy );
}
return Math . min ( set . size (), candies . length / 2 );
}
}
我们利用HashSet来解决此问题。 我们使用HashSet找出袋子中独特糖果的数量。 现在,可能出现每种类型的糖果超过1个的情况。在这种情况下,我们获得最大数量的独特糖果。 否则,我们只能使用唯一的值,直到要分发的糖果数量即candies.length/2
。
因此,从这种逻辑出发,我们的解决方案集中在一行中,在此一行中,获得的唯一值和candies.length/2
的数量最少。
这是HashSet可以帮助我们解决线性时间复杂度这类问题的方法之一。
From: https://dev.to/varunu28/a-leetcode-a-day-distribute-candies-9ai