LeetCode | 23. Merge k Sorted Lists merger k ordered array (C ++)

Title Description (Difficulty)

原题链接
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

algorithm

(Divide and Conquer) O ( m l o g n ) O (mlogn)

N = 6, combined 0-31-42-5: divide and conquer algorithm using, for example,
has been done before implementing merging two sorted linked list

Time complexity is O ( m l o g n ) O (mlogn) : n-list is the number, m is the maximum number of nodes in the two lists

C ++ code

/**
 * 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) {
        // Divide and Conquer Approach
        // odd:  n = 5   0-3 1-4 2        k = (n + 1) / 2
        // even: n = 6   0-3 1-4 2-5
        
        int n = lists.size();
        if (n == 0) return NULL;
        while(n > 1) {
            int k = (n + 1) / 2;
            
            for (int i = 0; i < n / 2; i ++) {
                lists[i] = mergeTwoLists(lists[i], lists[i + k]);
            }
            n = k;
        }
        
        return lists[0];    
    }
    
    // merge two lists
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        auto dummy = new ListNode(-1);
        auto p = dummy;
        
        while(l1 && l2) {
            if (l1->val <= l2->val) {
                p->next = l1;
                p = l1;
                l1 = l1->next;
            } else {
                p->next = l2;
                p = l2;
                l2 = l2->next;
            }
        }
        
        if (l1) p->next = l1;
        if (l2) p->next = l2;
        
        return dummy->next;
    }
    
    
};

Written in the last : my blog mainly on the field of computer science summarized knowledge of thinking, and review, to write each blog it is easy to understand my goal, sharing technology and knowledge is a pleasure , and I welcome everyone together with the exchange of learning, there can be no question in the comments area, but also look forward to in-depth exchanges with your (^ ∀ ^ ●)

Published 308 original articles · won praise 149 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_43827595/article/details/104538442