合并K个排序链表算法

学习地址B站https://www.bilibili.com/video/BV1mK411N7pu?from=search&seid=3121723007892517064
在这里插入图片描述

public class _003_23_合并K个链表 {
    //思路1  最笨的方法
    public ListNode mergeKLists1(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;

        //将所有节点添加到数组中
        List<ListNode> nodes = new ArrayList<>();
        for (ListNode list : lists) {
            while (list != null) {
                nodes.add(list);
                list = list.next;
            }
        }

        //对数组进行排序 (基于比较的排序,时间复杂度目前最好是O(nlogn),n是所有节点的数量)
        nodes.sort((ListNode node1, ListNode node2) -> {
            return node1.val - node2.val;
        });

        //将排好序的节点串起来
        ListNode head = new ListNode(0);
        ListNode cur = head;
        for (ListNode node : nodes) {
            cur = cur.next = node;
        }

        return head.next;

    }
}

在这里插入图片描述

//思路2  逐一比较
    public ListNode mergeKLists2(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        ListNode head = new ListNode(0);
        ListNode cur = head;

        while (true) {
            //最小链表节点所在的索引
            int minIndex = -1;
            for (int i = 0; i < lists.length; i++) {
                if (lists[i] == null) continue;

                if (minIndex == -1 || lists[i].val < lists[minIndex].val) {
                    minIndex = i;
                }
            } //O(k)
            // 所有链表节点已经串起来了
            if (minIndex == -1) break;

            cur = cur.next = lists[minIndex];
            lists[minIndex] = lists[minIndex].next;
        }// O(kn)

        return head.next;

    }

在这里插入图片描述

//思路3    逐一两两合并
    public ListNode mergeKLists3(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;

        for (int i = 1; i < lists.length; i++){
            lists[0] = mergeTwoLists(lists[0], lists[i]);
        }

        return lists[0];
    }
    //虚拟头结点
    private ListNode head = new ListNode(0);
    public ListNode mergeTwoLists(ListNode k1, ListNode k2) {
        if (k1 == null) return k2;
        if (k2 == null) return k1;

        head.next =null;
        ListNode cur = head;
        while (k1 != null && k2 != null) {
            if (k1.val <= k2.val) {
                cur = cur.next = k1;
                k1 = k1.next;
            }else {
                cur = cur.next = k2;
                k2 = k2.next;
            }
        }
        if (k1 == null){
            cur.next = k2;
        }else if (k2 == null){
            cur.next = k1;
        }

        return head.next;

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值