【刷题】23. 合并K个排序链表(Merge k Sorted Lists)

题目

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6

来源:力扣(LeetCode)https://leetcode-cn.com/problems/merge-k-sorted-lists

思路

暴力法

看到这个题熟悉Java基本类库的同学,第一时间会想到,遍历链表,用个List存起来,然后用Collections.sort排个序,然后再遍历这个List生成链表。本以为会超时,居然过了,真开心。

private ListNode merge(ListNode[] lists) {
    if (lists == null || lists.length == 0) {
        return null;
    }
    List<Integer> all = new ArrayList<>();
    for (ListNode list : lists) {
        ListNode node = list;
        while (node != null) {
            all.add(node.val);
            node = node.next;
        }
    }
    Collections.sort(all);
    if (all.isEmpty()) {
        return null;
    }
    ListNode head = new ListNode(all.get(0));
    ListNode temp = head;
    for (int i = 1; i < all.size(); i++) {
        temp.next = new ListNode(all.get(i));
        temp = temp.next;
    }
    return head;
}

两两合并

想到两两合并是因为之前做过一个两个链表的合并的题目,所以可以抄过来,加个循环即可,两个链表合并分治算法,递归搞的。就是将两个链表逐一向后遍历,左边的小就挪左边的,右边的小就挪右边的。

private ListNode merge1(ListNode[] lists) {
    if (lists == null || lists.length == 0) {
        return null;
    }
    if (lists.length == 1) {
        return lists[0];
    }
    ListNode res = lists[0];
    for (int i = 1; i < lists.length; i++) {
        res = mergeTwoList(res, lists[i]);
    }
    return res;
}


private ListNode mergeTwoList(ListNode left, ListNode right) {
    if (left == null) {
        return right;
    } else if (right == null) {
        return left;
    } else if (left.val < right.val) {
        left.next = mergeTwoList(left.next, right);
        return left;
    } else {
        right.next = mergeTwoList(left, right.next);
        return right;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kiba_zwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值