Merge k Sorted Lists

Q:

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

A:

时间复杂度大概是nLogk,n为所有节点数量,k是list的数量,利用归并,总是从头和尾选取两个list进行归并,并把结果放到头部,不需要额外空间。

leetcode的题目并不难,关键是如何写出漂亮的代码。

努力中。。。。

class Solution {
 public:
  ListNode *mergeKLists(vector<ListNode *> &lists) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if (lists.empty()) {
      return NULL;
    }
    while (lists.size() > 1) {
      int len = lists.size();
      int new_size = (len + 1)/ 2;
      for (int i = 0; i < len / 2; ++i) {
        lists[i] = mergeTwoLists(lists[i], lists[len - i - 1]);       
      }   
      lists.resize(new_size);
    }   
    return lists.back();
  }

 private:
  ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    ListNode* head = NULL;
    ListNode** cur = &head;
    while (l1 && l2) {
      if (l1->val <= l2->val) {
        *cur = l1;
        l1 = l1->next;
      } else {
        *cur = l2;
        l2 = l2->next;
      }   
      cur = &((*cur)->next);
    }   
    if (l1) *cur = l1;
    if (l2) *cur = l2;
    return head;
  }
};

 

 

posted @ 2013-06-13 16:58  dmthinker  阅读(90)  评论(0)    收藏  举报