leetcode--Merge k Sorted Lists

1.题目描述

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

2.解法分析

这个是归并排序的一个变种,很明显用分治法做比较好。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(lists.empty())return NULL;
        
        int curLen=lists.size();
        
        while(curLen!=1)
        {
            int i=0;
            for(;i<curLen/2;++i)
            {
                lists[i]=merge2Lists(lists[2*i],lists[2*i+1]);
            }
            
            if(curLen%2==1)lists[i]=lists[2*i];
            
            curLen=(curLen+1)/2;
        }
        
        return lists[0];
        
    }
    
    //合并两个list
    ListNode *merge2Lists(ListNode *list1,ListNode *list2)
    {
        if(list1==NULL)return list2;
        if(list2==NULL)return list1;
        ListNode *cur1=list1;
        ListNode *cur2=list2;
        
        //为是代码看上去整洁,定义一个统一的头指针
        ListNode *head=new ListNode(-1);
        ListNode *prev=head;
        prev->next=cur1;
        //逻辑上将list2插入到list1中
        while(cur1!=NULL&&cur2!=NULL)
        {
            while(cur1!=NULL&&cur1->val<cur2->val)
            {
                prev=cur1;
                cur1=cur1->next;
            }
            //当前list2中即将要插入到list1的节点值比list1中所有节点都大
            if(cur1==NULL)break;
            
            //找到插入点
            prev->next=cur2;
            cur2=cur2->next;
            prev->next->next=cur1;
            prev=prev->next;
        }
        
        //list2中其余部分
        if(cur1==NULL&&cur2!=NULL)
        {
            prev->next=cur2;
        }
        prev=head->next;
        delete head;
        return head->next;
        
        
        
    }
};
posted @ 2013-08-22 23:14  曾见绝美的阳光  阅读(229)  评论(0编辑  收藏  举报