349 intersection of two arrays

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

    Each element in the result must be unique.
    The result can be in any order.



#define HASH_SIZE 100
//hash arrary + linked list
struct listnode{
    int val;
    int found;
    struct listnode *next;
};

int hash_func(int value)
{
    return abs(value)%HASH_SIZE;
}


int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {

    struct listnode ** hash = calloc(HASH_SIZE, sizeof(struct listnode*));
    int index ;
    int * array = calloc(nums1Size<nums2Size?nums1Size:nums2Size, sizeof(int));
    int count = 0;
    struct listnode * dummyhead;
    for(int i = 0 ; i < HASH_SIZE; i++){
        hash[i] = malloc(sizeof(struct listnode));
        hash[i]->next = NULL;
    }
    int duplicate = 0;
    for(int i = 0 ; i < nums1Size; i++){
        index  = hash_func(nums1[i]);
        dummyhead = hash[index];
        struct listnode * node = malloc(sizeof(struct listnode));
        node->val = nums1[i];
        node->next = NULL;
        node->found = 0;
        while(dummyhead->next!=NULL){
              if(dummyhead->next->val == nums1[i]){
                    duplicate=1;
                    break;
                    
              }
              dummyhead = dummyhead->next;
        }
        if(duplicate){
            free(node);
            duplicate = 0;
        }else
            dummyhead->next = node;

    }

    for(int i = 0 ; i < nums2Size; i++){
        index  = hash_func(nums2[i]);
        dummyhead = hash[index];

        while(dummyhead->next!=NULL){
              if(dummyhead->next->val == nums2[i] && dummyhead->next->found == 0){
                    
                    array[count++] = nums2[i];
                    dummyhead->next->found = 1 ;
              }
              dummyhead = dummyhead->next;
        }
    }

    *returnSize = count;

    return array;
    
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容