Answer:
1. Using heap. O(k*n*logk).
class Solution {
private:
struct cmp{
bool operator()(ListNode* lhs, ListNode *rhs){
if(lhs->val < rhs->val) return false;
else return true;
}
};
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
int K = lists.size();
if (K == 0) return NULL;
else if (K == 1) return lists[0];
ListNode *listHead(NULL), *listRear(NULL);
ListNode *node(NULL);
priority_queue<ListNode*, vector<ListNode*>, cmp> h;
// push K list heads into heap
for(int i=0; i<K; ++i)
if(lists[i] != NULL){
h.push(lists[i]);
lists[i] = lists[i]->next;
}
while(!h.empty()){
//pop the min of k nodes in the heap.
node = h.top(); h.pop();
if(node->next)
h.push(node->next);
//insert node into new list.
if(listRear){
listRear->next = node;
listRear = listRear->next;
}
else{
listHead = listRear = node;
}
}
return listHead;
}
};
2. Merge Lists using Divide and Conquer. O(k*n*logk).
- public ListNode mergeKLists(ArrayList<ListNode> lists) {
- if(lists==null || lists.size()==0)
- return null;
- return helper(lists,0,lists.size()-1);
- }
- private ListNode helper(ArrayList<ListNode> lists, int l, int r)
- {
- if(l<r)
- {
- int m = (l+r)/2;
- return merge(helper(lists,l,m),helper(lists,m+1,r));
- }
- return lists.get(l);
- }
- private ListNode merge(ListNode l1, ListNode l2)
- {
- ListNode dummy = new ListNode(0);
- dummy.next = l1;
- ListNode cur = dummy;
- while(l1!=null && l2!=null)
- {
- if(l1.val<l2.val)
- {
- l1 = l1.next;
- }
- else
- {
- ListNode next = l2.next;
- cur.next = l2;
- l2.next = l1;
- l2 = next;
- }
- cur = cur.next;
- }
- if(l2!=null)
- cur.next = l2;
- return dummy.next;
- }
No comments:
Post a Comment