Merge k Sorted Lists, mergesortedlists

Source: Internet
Author: User

Merge k Sorted Lists, mergesortedlists

Question: MergeKSorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Idea: My first thought was to merge and sort the linked lists in lists, so the Time complexity is o (n). n is the data in all linked lists, and the result is Time Limit Exceeded... I didn't think of other methods that are too good for the moment. I hope you can give me some ideas. I will give you a brick first. The following is my UNAC code:

 

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 public: 11 ListNode * mergeKLists (vector <ListNode *> & lists) {12 if (lists. size () = 0) return NULL; 13 14 ListNode * pList = lists [0]; 15 16 vector <ListNode * >:: iterator it = lists. begin () + 1; 17 for (; it! = Lists. end (); ++ it) 18 {19 pList = MergeLists (pList, * it); 20} 21 22 // for (int I = 1; I <lists. size (); I ++) 23 // {24 // pList = MergeLists (pList, lists [I]); 25 //} 26 27 return pList; 28} 29 30 ListNode * MergeLists (ListNode * list1, ListNode * list2) 31 {32 ListNode * pList = new ListNode (0); 33 ListNode * pHead = pList; 34 35 while (list1 & list2) 36 {37 if (list1-> val> list2-> val) 38 {39 pList-> next = list2; 40 list2 = list2-> next; 4 1} 42 else43 {44 pList-> next = list1; 45 list1 = list1-> next; 46} 47 pList = pList-> next; 48} 49 50 if (! List1) 51 {52 pList-> next = list2; 53} 54 if (! List2) 55 {56 pList-> next = list1; 57} 58 59 pList = pHead; 60 pList = pList-> next; 61 pHead-> next = NULL; 62 delete (pHead); 63 64 return pList; 65} 66 };View Code

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.