1. 程式人生 > 實用技巧 >leetCode 23

leetCode 23

1.題目描述

  1. 合併K個排序連結串列
    合併 k 個排序連結串列,返回合併後的排序連結串列。請分析和描述演算法的複雜度。

示例:

輸入:
[
1->4->5,
1->3->4,
2->6
]
輸出: 1->1->2->3->4->4->5->6

--

2.思路

思路:分而治之
有點像歸併排序
程式碼如下

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* merge(ListNode *l1 , ListNode * l2) {
        auto dummy = new ListNode(-1);
        auto r = dummy;
        while(l1 && l2 ) {
            if(l1 -> val < l2 -> val) {
                r->next = l1;
                l1 = l1 -> next;
            }
            else {
                r -> next = l2;
                l2 = l2 -> next;
            }
            r = r -> next;
        }
        r -> next = nullptr;
        if(l1) r->next = l1;
        if(l2) r -> next = l2;
        return dummy -> next;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.size() == 0) return nullptr;
        if(lists.size() == 1) return lists[0];
        int mid = lists.size() / 2;
        vector<ListNode*> l1(lists.begin(),lists.begin()+mid);
        vector<ListNode*> l2(lists.begin()+mid,lists.end());
        //for(auto ele : l1) cout<<ele->val<<",";
       // cout<<"-----------"<<endl;
        //for(auto ele : l2) cout<<ele->val<<",";
        ListNode *ml1 = mergeKLists(l1);
        ListNode *ml2 = mergeKLists(l2);
        return merge(ml1,ml2);
    }
};

合併一個兩個連結串列O(n)
分而治之要O(logn)
所以時間複雜度為O(nlogn)