题解 | 合并k个已排序的链表

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <algorithm>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 可以利用现有
     *
     * @param lists ListNode类vector
     * @return ListNode类
     */

    static bool compareLess(ListNode* l1, ListNode* l2) {
        return l1->val > l2->val;
    }

    ListNode* mergeByHeap(vector<ListNode*>& lists) {
        // write code here
        ListNode fake(0);
        ListNode* cur = &fake;

        vector<ListNode*> data;
        for (const auto& item : lists) {
            if (item) {
                data.push_back(item);
            }
        }

        make_heap(data.begin(), data.end(), compareLess);

        while (data.size()) {
            cur->next = data.front();
            pop_heap(data.begin(), data.end(), compareLess);
            data.pop_back();
            cur = cur->next;
            if (cur->next) {
                data.push_back(cur->next);
                push_heap(data.begin(), data.end(), compareLess);
            }
        }


        return fake.next;
    }

    ListNode* mergeTwoSortedLists(ListNode* L1, ListNode* L2) {
        if (L1 == nullptr) // 出口遍历选择
            return L2;
        if (L2 == nullptr)
            return L1;
        if (L1->val <= L2->val) {
            L1->next = mergeTwoSortedLists(L1->next,
                                           L2); // 此时L1的val值小,那么它的next需要指向下一个大的值
            return L1;
        } else {
            L2->next = mergeTwoSortedLists(L1, L2->next);
            return L2;
        }
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        // 方法一
        //return mergeByHeap(lists);

        // 方法二
        return mergeByMergeSort(lists);
    }

    // 方法二
    ListNode* mergeByMergeSort(vector<ListNode*>& lists) {
        if (lists.empty()) {
            return nullptr;
        }

        while (lists.size() > 1) {
            auto sorted_list = mergeTwoSortedLists(lists.back(),
                                                   *std::prev(std::prev(lists.end())));
            lists.pop_back();
            lists.pop_back();
            lists.push_back(sorted_list);
        }
        return lists.front();
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务