Leetcode Merge k Sorted Lists

來源:互聯網
上載者:User

標籤:des   style   blog   color   for   c++   

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

合并k個排序列表

解題思路是:

取出 k個元素進行堆排序,每次取出最小的元素,插入鏈表中即可

注意本題利用了c++得優先權隊列,優先權隊列底層是用堆實現的

注意本題中一個特殊的測試案例是[{}]

注意vector為空白時表示為[],而不是[{}],而後者是大小為1的vector,其中元素是null 指標

放入優先權隊列時進行判斷是否為空白

放入優先權隊列的元素是ListNode *, 而不是int,主要是保持原有鏈表的地址,避免地址失效,而且放入int話,之後又重新new ListNode(int)開銷還是比較大的.

對放入優先權隊列中得ListNode*要定義一個比較函數對象,如果不定義的話,比較的是地址大小

class Solution {public:    struct cmp{        bool operator()(const ListNode* a, const ListNode* b) const{            return a->val > b->val;        }    };        ListNode *mergeKLists(vector<ListNode *> &lists) {        if(lists.empty()) return NULL;        priority_queue<ListNode*,vector<ListNode*>,cmp> pq;        ListNode *head = new ListNode(0), *pre = head;        for(int i = 0 ; i < lists.size(); ++ i){            if(lists[i]) pq.push(lists[i]);        }        while(!pq.empty()){            ListNode* node = pq.top(); pq.pop();            if(node->next) pq.push(node->next);            pre->next = node;            pre = node;        }        pre->next = NULL;        return head->next;    }};

 第二種方法是二分的方法,每次取兩個ListNode * 進行合并

程式中運用了隊列,每次從隊列中取出兩個元素然後合并,將合并後的元素又放入隊列,直到隊列只剩小一個元素為止即可

class Solution {public:    ListNode *mergeLists(ListNode* p,ListNode* q){        ListNode* head = new ListNode(0),*pre = head;        while(p && q){            if(p->val < q ->val){                ListNode *tmp = p->next;                p->next = pre->next;                pre->next = p;                pre = p;                p = tmp;            }else{                ListNode *tmp = q->next;                q->next = pre->next;                pre->next = q;                pre = q;                q = tmp;            }        }        pre->next = NULL;        if(p) pre->next = p;        if(q) pre->next = q;         return head->next;    }    ListNode *mergeKLists(vector<ListNode *> &lists) {        if(lists.empty()) return NULL;        queue<ListNode *> que;        for(int i = 0 ; i < lists.size(); ++ i){            if(lists[i]) que.push(lists[i]);        }        while(que.size()>1){            ListNode* p = que.front();que.pop();            ListNode* q = que.front();que.pop();            que.push(mergeLists(p,q));        }        return que.front();    }};

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.