LeetCode 23 - 合并有序链表(困难链表)

题目链接https://leetcode-cn.com/problems/merge-k-sorted-lists/题目:

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.


Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]


Example 2:

Input: lists = []        Output: []


Example 3:

Input: lists = [[]]        Output: []

思路:

链表的操作是这道题的难点,k个链表的操作会更加困难,所以我们可以先从两个链表着手。第一种想法是先写出一个能合并两个链表的算法,然后对k个链表执行k-1次即可。空间复杂度为O(1),但时间复杂度较高O(k^{2}n)。

对于链表的操作有几点需要注意:对于会被修改的链表,需要创建一个指针来记录原链表的起始位置(或者修改的位置),否则最后可能找不到起始位置在哪里。

题解:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode *a, ListNode *b) {
        if(a==nullptr) return b;
        if(b==nullptr) return a;

        ListNode head, *tail = &head;   // "head" is the head of the answer list
        // head must be saved, therefore we have pointer tail which can be moved

        while (a && b) {
            // each time we put a new val at the tail of the answer list
            if (a->val < b->val) {
                tail->next = a; a = a->next;
            } else {
                tail->next = b; b = b->next;
            }
            tail = tail->next;
        }

        // put the remaining list to tail of the answer list
        if(a==nullptr) tail->next=b;
        else tail->next=a;

        return head.next;
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode *ans = nullptr;
        for (size_t i = 0; i < lists.size(); ++i) {
            ans = mergeTwoLists(ans, lists[i]);
        }
        return ans;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值