llllmz

导航

454. 四数相加 II C

自己写了一个hash表。

原来学过的数据结构关于hash的那章还是有实际用的,不是书架子。

typedef struct node{
    int sum;
    int count;
    struct node* repeatnext;
}hash;

void init_hashtable(hash h[]){
    for(int i=0;i<127;i++){
        h[i].sum=0;
        h[i].count=0;
        h[i].repeatnext=NULL;
    }
}

hash* find_hash(hash h[],int i){
    int t=abs(i) % 127;
    if(h[t].sum==i){
        return &h[t];
    }
    hash* tem=h[t].repeatnext;
    while(tem){
        if(tem->sum==i) return tem;
        tem=tem->repeatnext;
    }
    return NULL;
}

void inset_hash(hash h[],int i){
    int t=abs(i)%127;
    if(h[t].count==0){
        h[t].sum=i;
        h[t].count++;
    }else{
        if(find_hash(h,i)){
            find_hash(h,i)->count++;
        }else{
            hash* tem=(hash*)malloc(sizeof(hash));
            tem->sum=i;
            tem->count=1;
            tem->repeatnext=h[t].repeatnext;
            h[t].repeatnext=tem;
        }
    }
}

int fourSumCount(int* nums1, int nums1Size, int* nums2, int nums2Size, int* nums3, int nums3Size, int* nums4, int nums4Size){
    hash h[127];
    init_hashtable(h);
    int n=nums1Size;
    int sum=0;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            inset_hash(h,nums1[i]+nums2[j]);
        }
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            int x=nums3[i]+nums4[j];
            if(x>0){
                if(find_hash(h,0-x)){
                    sum+=find_hash(h,0-x)->count;
                }
            }else{
                if(find_hash(h,abs(x))){
                    sum+=find_hash(h,abs(x))->count;
                }
            }
        }
    }
    return sum;
}

结果:

posted on 2024-02-28 22:05  神奇的萝卜丝  阅读(23)  评论(0)    收藏  举报