leetcode-23

https://leetcode-cn.com/problems/merge-k-sorted-lists/

思路1:粗暴方法,纵向merge

ListNode* mergeKLists(vector<ListNode*>& lists) {
    ListNode *head;
    ListNode *res = new ListNode();
    head = res;
    while(true) {
        int min_value = INT_MAX;
        for (int i = 0; i < lists.size(); i++) {
            if (lists[i]) {
                min_value = min(min_value, lists[i]->val);
            }
        }
        if (min_value == INT_MAX) {
            return head->next;
        }
        for (int i = 0; i < lists.size(); i++) {
            if (lists[i] && lists[i]->val == min_value) {
                ListNode *temp;
                temp = lists[i]->next;
                res->next = lists[i];
                res = res->next;
                lists[i] = temp;
            }
        }
    }
    return head->next;
}

思路2:分支,底层两两合并,分治合并典型框架

ListNode* mergeTwuLists(ListNode* l1, ListNode* l2) {
    if (l1 == NULL) {
        return l2;
    }
    if (l2 == NULL) {
        return l1;
    }
    ListNode *res = new ListNode();
    ListNode *head;
    head = res;
    while(l1 && l2) {
        if (l1->val > l2->val) {
            ListNode *temp;
            temp = l2->next;
            res->next = l2;
            res = res->next;
            l2 = temp;
        } else {
            ListNode *temp;
            temp = l1->next;
            res->next = l1;
            res = res->next;
            l1 = temp;
        }
    }
    while(l1) {
        ListNode *temp;
        temp = l1->next;
        res->next = l1;
        res = res->next;
        l1 = temp;
    }
    while(l2) {
        ListNode *temp;
        temp = l2->next;
        res->next = l2;
        res = res->next;
        l2 = temp;
    }
    return head->next;
}

ListNode* merge(vector<ListNode*>& lists, int start, int end) {
    if (start == end) {
        return lists[start];
    }
    int mid = (start + end ) / 2;
    ListNode* l1 = merge(lists, start, mid);
    ListNode* l2 = merge(lists, mid + 1, end);
    return mergeTwuLists(l1, l2);
}

ListNode* mergeKLists(vector<ListNode*>& lists) {
    if (lists.size() == 0) {
        return NULL;
    }
    return merge(lists, 0 , lists.size() - 1);
}

猜你喜欢

转载自blog.csdn.net/shushi6969/article/details/113753090