23 合并K个有序链表

合并K个链表

暴力

 ListNode *mergeKLists(vector<ListNode *> &lists) {
        auto be = lists.begin();
        while (be != lists.end())
            if (be[0] == nullptr)
                be = lists.erase(be);
            else
                ++be;
        if (lists.empty())
            return nullptr;
        ListNode *head(new ListNode(0)), *temp = head;
        while (lists.size() > 1) {
            auto it = lists.begin() + 1, min = lists.begin();
            while (it != lists.end()) {
                if (it[0]->val < min[0]->val)
                    min = it;
                ++it;
            }
            temp->next = min[0];
            temp = temp->next;
            if (min[0]->next == nullptr)
                lists.erase(min);
            else
                min[0] = min[0]->next;
        }
        temp->next = lists[0];
        return head->next;
    }

善用vector

class Solution {
public:
    bool cmp(const ListNode *&p1, const ListNode *&p2) {
        return p1->val < p2->val;
    }

    ListNode *mergeKLists(vector<ListNode *> &lists) {
        vector<ListNode *> vec;
        for (auto head : lists) {
            while (head) {
                vec.push_back(head);
                head = head->next;
            }
        }
        if (vec.empty())
            return nullptr;
        if (vec.size() == 1)
            return vec[0];
        std::sort(vec.begin(), vec.end(), cmp);
        for (int i = 1; i < vec.size(); ++i)
            vec[i - 1]->next = vec[i];
        vec[vec.size() - 1]->next = nullptr;
        return vec[0];
    }
};

分治

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode dummy(0);
        dummy.next = l1;
        ListNode *cur = &dummy;

        while (l2) {
            while (cur->next && cur->next->val <= l2->val)
                cur = cur->next;
            l1 = cur->next;
            cur->next = l2;
            l2 = l1;
        }
        return dummy.next;
    }


    ListNode *mergeKLists(vector<ListNode *> &lists) {
        if (lists.empty())
            return nullptr;
        if (lists.size() == 1)
            return lists[0];
        if (lists.size() == 2)
            return mergeTwoLists(lists[0], lists[1]);
        size_t mid = lists.size() / 2 ;
        vector<ListNode*> vec1(lists.begin(),lists.begin()+mid);
        ListNode *l1 = mergeKLists(vec1);
        vector<ListNode*> vec2(lists.begin()+mid,lists.end());
        ListNode *l2 = mergeKLists(vec2);
        return mergeTwoLists(l1, l2);
    }
};
原文地址:https://www.cnblogs.com/INnoVationv2/p/10171619.html