LeetCode 23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.


Two method: 1: merge one by one. 2: multiset.


Method1: merge one by one.

ListNode* merge(ListNode* l1, ListNode* l2) {
  if(!l1) return l2;
  if(!l2) return l1;
  ListNode* head = NULL;
  ListNode* currNode = NULL;
  ListNode* p = l1;
  ListNode* q = l2;
  while(p && q) {
    ListNode* node;
    if(p->val < q->val) {
      node = p;
      p = p->next;
    } else {
      node = q;
      q = q->next;
    }
    if(head = NULL) head = currNode = node;
    else {
      currNode->next = node;
      node->next = NULL;
      currNode = node;
    }
  }
  if(p) currNode->next = p;
  if(q) currNode->next = q;
  return head;
}



ListNode* mergeKLists(vector<ListNode*>& lists) {
  if(lists.size() == 0) return NULL;'
  ListNode* head = lists[0];
  for(int i = 1; i < lists.size(); ++i) {
    head = merge(head, lists[i]);
  }
  return head;
}  

Method2: multiset.

struct comparator : public binary_functin<ListNode*, ListNode*, bool> {
  bool operator() (const ListNode* a, ListNode* b) {
    return a->val < b->val;
  }
};

ListNode* mergeKLists(vector<ListNode*>& lists) {
  multiset<ListNode*, comparator> S;
  for(int i = 0; i < lists.size(); ++i) {
    if(lists[i]) {
      S.insert(lists[i]);
    }
  }

  ListNode* head = NULL;
  ListNode* tail = NULL;
  while(!S.empty()) {
    ListNode* node = S.begin();
    S.erase(node);
    if(!head) head = tail = node;
    else tail = tail->next = node;
    if(node->next) {
      S.insert(node->next);
    }
  }
  return head;
}


你可能感兴趣的:(LeetCode 23. Merge k Sorted Lists)