Why this code can work and that can't ?any suggestion??


  • 0
    X

    //this can work

    typedef struct node_s node;
        struct node_s {
        int val;
        int idx;
        node*next;
    };
    
     typedef struct {
       int     size;
       node    **table;
    }hash;
    
    int myabs(int a,int b)
    {
    return a>b?a-b:b-a;
    }
    int insertnode(hash*h,node*i,int k)
    {
    int index=i->val%(h->size);
    index=index>=0?index:-index;
    node*p=h->table[index];
    while(p){
        if(p->val==i->val&&myabs(i->idx,p->idx)<=k) return 0;
        p=p->next;
    }
    i->next=h->table[index];
    h->table[index]=i;
    return 1;
    }
    bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
     if(numsSize<=1) return false;
    int i;
    hash    *h;
    node    *n;
    if((h=malloc(sizeof(hash)))==NULL) return false;
    
    h->size=numsSize/2;
    h->table=(node**)malloc(sizeof(node*)*h->size);
    if(h->table==NULL) return false;
    
    for(i=0;i<h->size;i++) h->table[i]=NULL;
    
    for(i=0;i<numsSize;i++){
        n=malloc(sizeof(node));
        n->val=nums[i];
        n->idx=i;
        n->next=NULL;
        if((insertnode(h,n,k))==0) return true;
    }
    return false;
    

    }

    // but this can't

    typedef struct node_s node;
    struct node_s {
    int val,idx;
    node*next;
    };
    typedef struct {
    int size;
    node**table;
    }hash;
    int myabs(int a,int b)
    {
    return a>b?a-b:b-a;
    }
    int insertnode(hash*h,node*i,int k)
    {
    int index=i->val%h->size;
    index=index>=0?index:-index;
    node*p=h->table[index];
    while(p){
        if(p->val==i->val&&myabs(p->idx,i->idx)<=k) return 0;
        p=p->next;
    }
    
    i->next=h->table[index];
    h->table[index]=i;
    return 1;
    
    }
    
    bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
    if(numsSize<=1) return false;
    
    hash        h;//no need to malloc;
    int         i;
    node        *n;
    h.size=numsSize/2;
    h.table=(node**)malloc(sizeof(node*)*(h.size));
    
    for(i=0;i<numsSize;i++){
        n=malloc(sizeof(node));
        n->val=nums[i];
        n->idx=i;
        n->next=NULL;
        if((insertnode(&h,n,k))==0) return true;
    }
    return false;
    

    }

    the only difference is that i put the hash h in stack and hash *h in heap . but I guess this would not crashed my second code ,so why ??


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.