Merge k Sorted Lists

数据结构:优先队列

class Solution {
public:
    struct item{
        int i;
        ListNode *node;
        bool operator < (const item& a)const{
            return node -> val > a.node -> val;
        }
    };
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode *head = new ListNode(0);
        ListNode *node = head;
        priority_queue<item> pq;
        
        
        
        if(!lists.size()){
            return (ListNode*)NULL;
        }
        
        
        
        //初始化优先队列
        for(int i = 0; i < lists.size(); i++){
            if(lists[i] != NULL){
                item it;
                it.i = i;
                it.node = lists[i];
                pq.push(it);
            }
        }
        
        
        
        while(!pq.empty()){
            item t = pq.top();
            
            
            pq.pop();
            
            
            node -> next = t.node;
            
            
            if(lists[t.i] -> next != NULL){
                lists[t.i] = lists[t.i] -> next;
                t.node = lists[t.i];
                pq.push(t);
            }
            
            node = node -> next;
        }
        

        return head -> next;
    }
};

解决多路归并问题,把K个有序表合成一个有序表——用优先队列维护每个表的“当前元素”.如果有n个元素,则时间复杂度为O(nlogk);

(from:算法竞赛入门经典 - 刘汝佳)

 

posted @ 2016-11-12 20:26  中二病有所好转  阅读(140)  评论(0)    收藏  举报