Leetcode-merge k Sorted Lists

Source: Internet
Author: User

Topic:

Merge k Sorted Lists

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


Analysis:

With Multiset as a small Gan, the multiset begin is the smallest node of value.

Attention:

1, because I have defined the multiset of the ordering method (that is, the value of the node to sort), so that two different node pointers, if their value is equal, it will be judged as "the same node." and set is not allowed to duplicate values, so the following code can not use set, and with multiset!

2, the code I was used multiset, in fact, should be used with small Gan, but there is no ready-made Gan in C + + available, then lazy.


/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */struct Mysort {bool operator () (const listnode*const &AMP;A,CONST listnode*const &b) const {return a-&   gt;val<b->val; } };        Class Solution {public:listnode* mergeklists (vector<listnode*>& lists) {int size=lists.size ();        multiset<listnode*,mysort> table;        for (int i=0;i<size;++i) {if (lists[i]!=nullptr) Table.emplace (Lists[i]);        } ListNode Helper (0),*cur=&helper;            while (!table.empty ()) {listnode* tmp=*table.begin ();                      int smallest=tmp->val;            Cur->next=new ListNode (smallest);                     cur=cur->next;           if (tmp->next==nullptr) {table.erase (Table.begin ());             } else {    Table.erase (Table.begin ());            Table.emplace (Tmp->next);    }} return helper.next; }};


Leetcode-merge k Sorted Lists

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.