575. Distribute Candies

来源:互联网 发布:java面向对象知识点 编辑:程序博客网 时间:2024/06/08 00:44

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;}
原创粉丝点击