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

23. Merge k Sorted Lists

时间:2016-03-18 21:46:29      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

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

Subscribe to see which companies asked this question

 思路:类似归并排序,每个链表已经排好序了,现在只需要将各个链表合并成一个链表。要点:分而治之,最后合并。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
private:
    ListNode * merge_help(vector<ListNode*>&lists,int l,int r){
        if(l>=r)
            return lists[l];
        int mid=(l+r)/2;
        ListNode * left =merge_help(lists,l,mid);
        ListNode * right=merge_help(lists,mid+1,r);
        ListNode * temp =new ListNode (-1);
        ListNode *cur =temp;
        while(left&&right){
            if(left->val<=right->val){
                cur->next =left;
                left=left->next;
            }
            else{
                cur->next=right;
                right=right->next;
            }
            cur=cur->next;
        }
        if(left)
            cur->next=left;
        if(right)
            cur->next=right;
        return temp->next;
        
    }
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.size()==0)
            return NULL;
        return merge_help(lists,0,lists.size()-1);
            
    }
    
    
};

 

23. Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/zhoudayang/p/5293434.html

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