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;
}
网友评论