`

LeetCode 23 - Merge k Sorted Lists

 
阅读更多

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

 

public ListNode mergeKLists(List<ListNode> lists) {
    ListNode dummy = new ListNode(0);
    ListNode tail = dummy;
    Queue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>(){
        @Override
        public int compare(ListNode l1, ListNode l2) {
            return l1.val-l2.val;
        }
    });
    for(ListNode node: lists) {
        if(node !=null) queue.offer(node);
    }
    while(!queue.isEmpty()) {
        ListNode node = queue.poll();
        tail = tail.next = node;
        if(node.next != null) {
            queue.offer(node.next);
        }
    }
    return dummy.next;
}

 

Time Complexity: log(k) * n
k is number of list and n is number of total elements.

Space Compexity: k, the heap size

 

补充个C++的代码:

ListNode* mergeKLists(vector<ListNode*>& lists) {
    if(lists.size() == 0) return NULL;
    auto comp = [](ListNode* a, ListNode* b) {return a->val > b->val;};
    priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> pq(comp);
    for(auto it=lists.begin(); it!=lists.end(); ++it) {
        if(*it) pq.push(*it);
    }
    ListNode dummy(0), *node = &dummy;
    while(!pq.empty()) {
        ListNode *n = pq.top();
        pq.pop();
        node->next = n;
        node = n;
        if(n->next) {
            pq.push(n->next);
        }
    }
    return dummy.next;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics