[350].兩個數組的交集 II

 


題目

給定兩個數組,編寫一個函數來計算它們的交集。

示例 1:

輸入: nums1 = [1,2,2,1], nums2 = [2,2]
輸出: [2,2]

示例 2:

輸入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
輸出: [4,9]

 


函數原型

C 的函數原型:

int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){}

 


邊界判斷

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

}

 


算法設計:查找表

思路:因爲允許返回重複的元素,那元素出現的次數就重要了,所以,使用 map。

  • C語言有幾個數據結構庫都要 map:glib、uthash
#include<uthash.h>	/* Leetcode 支持的C語言哈希庫 */

struct hash{
    int key;
    int value;
    UT_hash_handle hh;
};
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    if(nums1>nums2) 
    	return intersect(nums2, nums2Size, nums1, nums1Size, returnSize);
    	
    int i;
    struct hash *table=NULL, *p=NULL;
    for(i=0; i<nums1Size; i++){
        HASH_FIND_INT(table, &nums1[i], p);
        
        if(!p){
            p=(struct hash*)malloc(sizeof(struct hash));
            p->key = nums1[i];
            p->value = 1;
            HASH_ADD_INT(table, key, p);
        }else{ 
        	p->value += 1;  // 找到直接添加
        }
    }
    *returnSize=0;  
    int *res=(int*)malloc(sizeof(int)*nums1Size);
    
    for(i=0; i<nums2Size; i++){
        HASH_FIND_INT(table, &nums2[i], p);
        
        if( p && p->value > 0){
        	res[(*returnSize)++] = nums2[i];
        	p->value --;
		}
    }
    free(p), p = NULL;
    return res;
}
  • 時間複雜度:Θ(n+m)\Theta(n+m)
  • 空間複雜度:Θ(min(n,m))\Theta(min(n, m))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章