首页 > 其他 > 详细

Merge k Sorted Lists

时间:2015-03-23 21:13:55      阅读:253      评论:0      收藏:0      [点我收藏+]

题目描述:

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

  因为之前做过Merge Two Sorted Lists,所以这道题也就显得不那么难了。

solution:

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode *mergeKLists(vector<ListNode *> &lists) {
    int n = lists.size();
    if(n == 0)
        return NULL;
    if(n == 1)
        return lists[0];
    if(n == 2)
        return mergeTwoLists(lists[0], lists[1]);
    vector<ListNode *>::iterator mid = lists.begin() + n / 2;
    vector<ListNode *> front(lists.begin(), mid);
    vector<ListNode *> back(mid, lists.end());
    return mergeTwoLists(mergeKLists(front), mergeKLists(back));
}

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
    if(l1 == NULL)
        return l2;
    if(l2 == NULL)
        return l1;
    ListNode *head = new ListNode(0);
    ListNode *p = head;
    while (l1 != NULL && l2 != NULL)
    {
        if (l1->val < l2->val)
        {
            p->next = l1;
            l1 = l1->next;
        }
        else
        {
            p->next = l2;
            l2 = l2->next;
        }
        p = p->next;
    }
    p->next = l1 ? l1 : l2;
    return head->next;
}

参考链接:https://leetcode.com/discuss/9279/a-java-solution-based-on-priority-queue

Merge k Sorted Lists

原文:http://www.cnblogs.com/gattaca/p/4360763.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!