Two Sum ---- why I get wrong answer?


  • 0
    L
    struct node {
         struct node *next;
         int num;
         int index;
    
     };
    
     struct node *head = NULL;
    
     void insert(struct node *p) {
          p->next = head;
          head = p;
     }
    
     int lookup(int Num) {
          struct node *q;
          q = head;
          while(q != NULL) {
              if(q->num == Num)
                  return q->index;
              q = q->next;
          }
          return -1;
     }
    
    int* twoSum(int* nums, int numsSize, int target) {
        int p,q;
        int *results;
        struct node* pNode;
        results = (int*)malloc(sizeof(int)*2);
        p = 0;
    
        while(p<numsSize) {
            if(lookup(target-*(nums+p)) == -1){
                struct node* pNode = (struct node*)malloc(sizeof(struct node));
                pNode->num = *(nums+p);
                pNode->index = p+1;
                insert(pNode);
            }
            else{
                results[0] = lookup(target-*(nums+p));
                results[1] = p + 1;
                printf("%d,%d",results[0],results[1]);
                return results;
            }
            p++;
        }
    }
    

    when I run code above on my own machine of linux, it can get right answer.


Log in to reply
 

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