23. Merge k Sorted Lists

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

Subscribe to see which companies asked this question

 思路:类似归并排序,每个链表已经排好序了,现在只需要将各个链表合并成一个链表。要点:分而治之,最后合并。

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. private:
  11. ListNode * merge_help(vector<ListNode*>&lists,int l,int r){
  12. if(l>=r)
  13. return lists[l];
  14. int mid=(l+r)/2;
  15. ListNode * left =merge_help(lists,l,mid);
  16. ListNode * right=merge_help(lists,mid+1,r);
  17. ListNode * temp =new ListNode (-1);
  18. ListNode *cur =temp;
  19. while(left&&right){
  20. if(left->val<=right->val){
  21. cur->next =left;
  22. left=left->next;
  23. }
  24. else{
  25. cur->next=right;
  26. right=right->next;
  27. }
  28. cur=cur->next;
  29. }
  30. if(left)
  31. cur->next=left;
  32. if(right)
  33. cur->next=right;
  34. return temp->next;
  35. }
  36. public:
  37. ListNode* mergeKLists(vector<ListNode*>& lists) {
  38. if(lists.size()==0)
  39. return NULL;
  40. return merge_help(lists,0,lists.size()-1);
  41. }
  42. };





原文地址:https://www.cnblogs.com/zhoudayang/p/5293434.html