12ms C solution using qsort


  • 1
    G
    int comp(const int *a, const int *b) {
        if (*a > *b) return 1;
        else if (*a < *b) return -1;
        else return 0;
    }
    
    bool containsDuplicate(int* nums, int numsSize) {
        if (numsSize < 2) {
            return false;
        }
        qsort(nums, numsSize, sizeof(int), comp);
        for (int i = 0; i < numsSize - 1; i++) {
            if (nums[i] == nums[i+1]) {
                return true;
            }
        }
        return false;
    }

  • 0
    J

    Solution in C,12ms ,using hash table

    #define HASHMAX 0XFFF
    #define HASH(val) ((val>0?val:-val)%HASHMAX)
    typedef struct node
    {
        int val;
        struct node* next;
    }Node;
    typedef Node** Hash;
    
    void initHash(Hash hash)
    {
        int i = 0;
        for(i = 0; i < HASHMAX; i++)
        {
            hash[i] = NULL;
        }
    }
    
    bool searchHash(Hash hash,int val)
    {
        int key = HASH(val);
        Node* node = hash[key];
        while(node)
        {
            if(node->val == val)
            return true;
            node = node->next;    
        }
    
        return false;
    }
    
    bool insertHash(Hash hash,int val)
    {
        if(searchHash(hash,val))
        {
            return false;
        }
        else
        {
            Node* node = (Node*)malloc(sizeof(Node));
            int key = HASH(val);
            node->val = val;
            node->next = NULL;
        
            if(hash[key] == NULL)
            {
                hash[key] = node;
            }
            else
            {
                node->next = hash[key];
                hash[key] = node;
            }
        
            return true;
        }
    }
    
    bool containsDuplicate(int* nums, int numsSize)
    {
        Node* hash[HASHMAX];
        int i;
    
        if(numsSize <= 1)
            return false;
        
        initHash(hash);
    
        for(i = 0; i < numsSize; i++)
        {
            if(!insertHash(hash,nums[i]))
            return true;
        }
        return false;
    }

Log in to reply
 

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