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;
}
349 intersection of two arrays
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Intersection of Two Arrays IIGiven two arrays, write a fu...
- Given two arrays, write a function to compute their inter...
- Javascript C++和Java想得太复杂了,看了下别人的解答 优解 Java,用哈希表解决了重复的问题 J...
- Given two arrays, write a function to compute their inter...
- Solution1:Hashset 思路:nums1保存到Hashset,nums2 check有无Time Co...