Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:每一个数字代表一种糖的一颗,一共有6颗糖,哥哥和妹妹在数量上平分糖,求妹妹最多得到糖的种类。要求输入的糖的个数都是偶数,在2~10000之间;糖的种类用-100000~100000之间的数字来表示。
此题的tag是hash table,用哈希表的方式解决。是一种比较常见的题型,但是需要注意数字的范围。用offset参数进行下标修正,否则会报insufficient space的错误。
以下是我的答案:
int distributeCandies(int* candies, int candiesSize) {
int i,half=candiesSize/2;
int count=0;
int offset=100000;
int* a=(int*)malloc(sizeof(int)*200001);
for(i=0;i<candiesSize;i++)
{
a[candies[i]+offset]++;
if(a[candies[i]+offset]==1) count++;
}
return (count>=half)?half:count;
}