C solution, hashtbl


  • 0
    J

    int distributeCandies(int* candies, int candiesSize) {
    int hashTbl[200002] = {0};
    int totalKind= 0;
    int index;

    for (index = 0; index < candiesSize; index++)
    {
    if (0 == (hashTbl[candies[index]+100000]))
    {
    totalKind++;
    hashTbl[candies[index]+100000]+=1;
    }
    }

    if (totalKind >= (candiesSize/2))
    {
    index = candiesSize/2;
    }
    else
    {
    index = totalKind;
    }
    return index;
    }

    actually , this case is judge that which one is smaller, the total kind of candies or the value of candiesSize/2, so the key is to find how many kind of candies.
    for C solution ,I used a large array to record the kind of candies, which just need O(n), but it takes a large memory,it's pretty ugly.
    so anybody can give a better solution with C? thanks.


  • 0
    Q

    why you set hashTbl[200002] ?
    i think 200001 is enough!!!!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.