leetcode,leetcodeoj

來源:互聯網
上載者:User

leetcode,leetcodeoj

題目:

Merge k Sorted Lists

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


分析:

用multiset作為小根堆,multiset的begin是value最小的結點。

注意:

1、由於我人為規定了multiset的排序方式(即用節點的value進行排序),使得兩個不同的節點指標,若它們的value相等,則會被判斷成“同一個節點”。而set是不允許重複值的,故以下代碼不能使用set,而用multiset!

2、代碼中我是用了multiset,實際上應該用小根堆的,只不過c++中沒有現成的小根堆可用,便偷懶了。


/** * 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 &a,const ListNode*const &b) const   {        return a->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;    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.