Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
#define HASH_SIZE 1000
struct hashnode{
int val;
int times;
struct hashnode *next;
};
struct hash{
struct hashnode * hash_table;
int (*hash_func)(int);
};
int hash_func(int val)
{
return abs(val)%HASH_SIZE;
}
void hash_add(struct hash * h, int val)
{
int index = h->hash_func(val);
struct hashnode *dummy = &(h->hash_table[index]);
if(dummy->next == NULL){
struct hashnode * node = calloc(1, sizeof(struct hashnode));
node->val = val;
node->times = 1;
dummy->next = node;
}else{
struct hashnode *p = dummy->next;
while(p){
if(p->val == val){
p->times += 1;
return;
}
p = p->next;
}
struct hashnode * node = calloc(1, sizeof(struct hashnode));
node->val = val;
node->times = 1;
node->next = dummy->next;
dummy->next = node;
}
}
struct hash * hash_init()
{
struct hash * h = calloc(1, sizeof(struct hash));
h->hash_table = calloc(HASH_SIZE, sizeof(struct hashnode));
h->hash_func = hash_func;
return h;
}
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
struct hash * h = hash_init();
int * ret = calloc(0, sizeof(int));
*returnSize = 0;
for(int i = 0; i < nums1Size; i++){
hash_add(h, nums1[i]);
}
for(int i = 0; i < nums2Size; i++){
int index = h->hash_func(nums2[i]);
struct hashnode *dummy = &(h->hash_table[index]);
if(dummy->next == NULL){
}else{
struct hashnode *p = dummy->next;
struct hashnode *prev = dummy;
while(p){
if(p->val == nums2[i]){
//save val. intersection node found
*returnSize += 1;
ret = realloc(ret, (*returnSize)*(sizeof(int)));
ret[*returnSize - 1] = nums2[i];
p->times -= 1;
if(0 == p->times){
//remove p
prev->next = p->next;
free(p);
}
}
p = p->next;
prev = prev->next;
}
}
}
return ret;
}
350. Intersection of Two Arrays II
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Intersection of Two Arrays IIGiven two arrays, write a fu...
- 原题是: Given two arrays, write a function to compute their ...
- Given two arrays, write a function to compute their inter...