LeetCode 23. Merge k Sorted Lists

LeetCode 23. Merge k Sorted Lists

题目

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

分析

把k个排列好的链表合并成一个返回,根据链表的特性,我决定采取以下策略:

  • 使用插入排序

  • 把其他链表插入第一个不为NULL的链表

不过感觉复杂度有点高为O(k^2 * n)…

代码实现

class Solution {
public:
    ListNode * mergeKLists(vector<ListNode*>& lists) {
        if (lists.size() == 0)return nullptr;
        int first = 0;
        while (lists[first] == nullptr)
        {
            first++;
            if (first == lists.size())return nullptr;
        }
        for (int index = first + 1; index < lists.size(); index++)
            lists[first] = mergeTwoLists(lists[first], lists[index]);
        return lists[first];
    }
private:
    //把l2合并到l1
    ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) {
        if (l2 == nullptr)return l1;
        //保证l1->val < l2->val
        if (l1->val > l2->val) {
            ListNode *temp = l2;
            l2 = l1;
            l1 = temp;
        }
        //p储存l1的头部
        ListNode *p = l1;
        /*l2插入l1*/
        while (l2 != nullptr)
        {
            ListNode *save;
            save = l2->next;
            insertValue(l1, l2);
            l2 = save;
        }
        return p;
    }
    void insertValue(ListNode *l1, ListNode *value)
    {
        //本函数会修改value指向位置,因此在调用前需保存value->next
        if (l1->next == nullptr)
        {
            l1->next = value;
            value->next = nullptr;
            return;
        }
        while (value->val >= l1->next->val)
        {
            l1 = l1->next;
            if (l1->next == nullptr)
            {
                l1->next = value;
                value->next = nullptr;
                return;
            }
        }
        ListNode *save;
        save = l1->next;
        l1->next = value;
        value->next = save;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值