My solution with c whoes runtime is 6ms ,can there anything improved


  • 0
    C
    typedef struct node
    {
      int key;
      int val;
      struct node *next;
    }node_t;
    
    typedef struct hash_table
    {
      node_t **nodes;
      int capacity;
    }hash_table_t;
    
    hash_table_t *new_hash_table(int length)
    {
      hash_table_t *hash = malloc(sizeof(hash_table_t));
      if(hash == NULL)
        return NULL;
      int i;
      hash->nodes = malloc(length * sizeof(*(hash->nodes)));
      if(hash->nodes == NULL)
      {
        free(hash);
        return NULL;
      }
      hash->capacity = length;
      for(i = 0; i < length; i++)
        hash->nodes[i] = NULL;
      return hash;
    }
    
    node_t *new_node(int key,int val)
    {
      node_t *node = malloc(sizeof(*node));
      if(node == NULL)
        return NULL;
      node->key = key;
      node->val = val;
      node->next = NULL;
      return node;
    }
    
    int hash_code(int key,int length)
    {
      if(key < 0)
        key = -key;
      return key%length;
    }
    
    int *twoSum(int numbers[], int n, int target) {
      int *index = malloc(2 * sizeof(int));
      int i,j;
      int a[n],hashcode;
    
      hash_table_t *hash = new_hash_table(n);
      if(hash == NULL)
        return NULL;
    
      node_t *node,*head;
      for(i = 0; i < n; i++)
      {
        a[i] = target - numbers[i];
    
        node = new_node(numbers[i],i);
        if(node == NULL)
          return NULL;
        hashcode = hash_code(numbers[i],n);
        head = hash->nodes[hashcode];
        if(head == NULL)
            hash->nodes[hashcode] = node;
        else
        {
          node->next = head;
          hash->nodes[hashcode] = node;
        }
    
      }
      for(i = 0; i < n; i++)
      {
        hashcode = hash_code(a[i],n);
        node = hash->nodes[hashcode];
        while(node != NULL && node->key != a[i])
          node = node->next;
        if(node != NULL && node->key == a[i])
        {
          if(i > node->val)
          {
            index[0] = node->val;
            index[1] = i;
            return index;
          }
          else if(i == node->val)
            continue;
          index[0] = i + 1;
          index[1] = node->val + 1;
          return index;
        }
    
      }
      
      for(i = 0; i < n; i++)
        free(hash->nodes[i]);
      free(hash->nodes);
      free(hash);
      
      return NULL;
    }

Log in to reply
 

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