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

Merge k Sorted Lists -- leetcode

时间:2014-11-27 20:36:39      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:algorithm

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

两种实现方法,第一种采用优先队列,第二种采用分治

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * use priority_queue
    class mycomparison
    {
    public:
        bool operator() (ListNode* lhs, ListNode* rhs)
        {
                return (lhs->val > rhs->val);
        }
    };
    
    ListNode *mergeKLists(vector<ListNode*> &lists) {
        
        priority_queue<ListNode*, vector<ListNode *>, mycomparison>  queue;
        for(int i = 0; i < lists.size(); i++){
            if(lists[i] != NULL)
                queue.push(lists[i]);
        }
        
        ListNode* head =NULL;
        ListNode* prev = NULL;
        while(!queue.empty())    
        {
            ListNode* tmp = queue.top();
            queue.pop();
            if(!prev)
            {
                head = tmp;
                prev = tmp;
            }
            else
            {
                prev->next= tmp;
                prev = tmp;
            }
            if(tmp->next)
                queue.push(tmp->next);
            
        }
        return head;
    }
    */
    //use divide and conquer algorithm
    //merge two list
    ListNode* Merge(ListNode* list1, ListNode* list2)
    {
        ListNode* head = NULL;
        if(list1 == NULL)
            return list2;
        if(list2 == NULL)
            return list1;
        if(list1->val < list2->val){
            head = list1;
            head->next = Merge(list1->next, list2);
        }    
        else{
            head = list2;
            head->next = Merge(list1, list2->next);
        }
        return head;
    }
    ListNode* MergeCore(vector<ListNode*> &lists, int left, int right)
    {
        if(left < right)
        {
            int mid = (right+left)/2;
            return Merge(MergeCore(lists, left, mid), MergeCore(lists, mid+1, right));
        }
        else if(left == right)
            return lists[left];
        return NULL;    
    }
    ListNode *mergeKLists(vector<ListNode*> &lists) {
        if(lists.size() <= 0)
            return NULL;
        return MergeCore(lists, 0, lists.size()-1);
    }
};



Merge k Sorted Lists -- leetcode

标签:algorithm

原文地址:http://blog.csdn.net/youxin2012/article/details/41550475

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