23. Merge k Sorted Lists
Posted ZHOU YANG
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
思路:类似归并排序,每个链表已经排好序了,现在只需要将各个链表合并成一个链表。要点:分而治之,最后合并。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { private: ListNode * merge_help(vector<ListNode*>&lists,int l,int r){ if(l>=r) return lists[l]; int mid=(l+r)/2; ListNode * left =merge_help(lists,l,mid); ListNode * right=merge_help(lists,mid+1,r); ListNode * temp =new ListNode (-1); ListNode *cur =temp; while(left&&right){ if(left->val<=right->val){ cur->next =left; left=left->next; } else{ cur->next=right; right=right->next; } cur=cur->next; } if(left) cur->next=left; if(right) cur->next=right; return temp->next; } public: ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.size()==0) return NULL; return merge_help(lists,0,lists.size()-1); } };
以上是关于23. Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章