码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Merge k Sorted Lists

时间:2014-12-20 11:34:12      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

Merge k Sorted Lists

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

 

多路归并。

1、用make_heap函数维护一个大小为k的最小堆。

注:由于默认是最大堆,因此需要自定义compare函数,注意定义为static或者全局函数。

因为make_heap是全局函数,不能调用非静态成员函数。

2、取出最小元素(即lists[0]),用pop_heap函数将最小元素移到最后

3、若原lists[0],即当前的lists[last]还有后继结点,则用push_heap将其后继结点调整入堆。

否则该链表归并完毕,删除。

 

重复2、3直到所有链表都归并完毕。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    static bool comp(const ListNode* n1, const ListNode* n2)
    {
        return n1->val > n2->val;   // > builds minimum heap. default < builds maximum heap
    }
    
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        //remove NULL lists
        vector<ListNode*>::iterator it = lists.begin();
        while(it != lists.end())
        {
            if(*it == NULL)
            //empty ListNode
                lists.erase(it);    //return the iterator to the next element
            else
                it ++;
        }
        
        if(lists.empty())
        //all empty
            return NULL;
            
        //make minimum heap
        make_heap(lists.begin(), lists.end(), comp);
        ListNode* newhead = new ListNode(-1);
        ListNode* tail = newhead;
        while(!lists.empty())
        {
            tail->next = lists[0];
            tail = tail->next;
            
            //remove the minimum element to the last position, that is lists[last]
            pop_heap(lists.begin(), lists.end(), comp);
            
            int last = lists.size()-1;
            if(lists[last]->next != NULL)
            {//lists[last] has been inserted into the result, and remove it, retrieve the next element
                lists[last] = lists[last]->next;
                //place new lists[last] into right position of heap
                push_heap(lists.begin(), lists.end(), comp);
            }
            else
            //lists[last] is all in result, remove it
                lists.pop_back();
        }
        return newhead->next;
    }
};

技术分享

 

【LeetCode】Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/ganganloveu/p/4175111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!