LeetCode-23-Merge k Sorted Lists

Posted 无名路人甲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-23-Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。

算法描述:

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

解题思路:分治法。

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.size()==0) return nullptr;
        int left = 0;
        int right = lists.size()-1;
        return sortMerge(lists, left, right);
    }
    
    ListNode* sortMerge(vector<ListNode*>& list, int left, int right){
        if(left == right) return list[left];
        int mid = left + (right - left) / 2;
        ListNode* l1 = sortMerge(list, left, mid);
        ListNode* l2 = sortMerge(list, mid+1, right);
        return merge(l1,l2);
    }
    
    ListNode* merge(ListNode* l1, ListNode* l2){
        ListNode* dup = new ListNode(-1);
        ListNode* cur = dup;
        while(l1!=nullptr&&l2!=nullptr){
            if(l1->val < l2->val){
                cur->next = l1;
                l1=l1->next;
            }else{
                cur->next = l2;
                l2=l2->next;
            }
            cur=cur->next;
        }
        if(l1!=nullptr) cur->next = l1;
        if(l2!=nullptr) cur->next = l2;
        return dup->next;
    }

 

以上是关于LeetCode-23-Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

[LeetCode]23. Merge k Sorted Lists

leetcode23. Merge k Sorted Lists

leetCode 23. Merge k Sorted Lists

leetcode 23. Merge k Sorted Lists

LeetCode-23-Merge k Sorted Lists