题目地址:
https://leetcode.com/problems/distribute-candies/
Alice有 n n n个糖果,第 i i i个糖果的种类是 c [ i ] c[i] c[i],她想吃不同种类的糖果,最多吃 n / 2 n/2 n/2个。问她最多能吃多少个糖果。
代码如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int distributeCandies(int[] candyType) {
Set<Integer> set = new HashSet<>();
for (int x : candyType) {
set.add(x);
}
return Math.min(set.size(), candyType.length / 2);
}
}
时空复杂度 O ( n ) O(n) O(n)。