23. Merge k Sorted Lists

这是一篇关于LeetCode第23题的解题报告,题目要求合并k个已排序的链表。文章首先介绍了直接依次合并的简单方法,但这种方法的时间复杂度较高,实际运行时间较慢。接着,作者提出了使用归并排序策略进行优化,通过拆分和两两合并,显著提高了运行效率,最终的解决方案在Java在线提交中,运行时间和内存使用都大幅优于平均表现。
摘要由CSDN通过智能技术生成

题目:23. Merge k Sorted Lists 合并k个排序的list

难度:困难

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

题意解析:

将k个有序的list进行合并然后返回一个排好序的list

解题思路一:

依次合并,时间复杂度较高。

public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0)
            return null;
        if(lists.length == 1)
            return lists[0];
        else {
            ListNode listNode = lists[0];
            ListNode node = listNode;
            for (int i = 1; i < lists.length; i++) {
                ListNode listNode1 = mergeTwoLists(listNode, lists[i]);
                listNode = listNode1;
            }
            return listNode;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2){
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        if(l1.val <= l2.val){
            l1.next = mergeTwoLists(l1.next,l2);
            return l1;
        }else{
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }
    }

提交代码之后:

Runtime: 297 ms, faster than 5.05% of Java online submissions for Merge k Sorted Lists.

Memory Usage: 48.3 MB, less than 5.60% of Java online submissions for Merge k Sorted Lists.

 

解题思路二:

采用归并的思想,将其进行拆分,然后两两合并。

public ListNode mergeKLists(ListNode[] lists) {
        return partion(lists,0,lists.length-1);
        
    }
    public static ListNode partion(ListNode[] lists,int s,int e){
    if(s==e)  return lists[s];
    if(s<e){
        int q=(s+e)/2;
        ListNode l1=partion(lists,s,q);
        ListNode l2=partion(lists,q+1,e);
        return merge(l1,l2);
    }else
        return null;
    }

    //This function is from Merge Two Sorted Lists.
    public static ListNode merge(ListNode l1,ListNode l2){
        if(l1==null) return l2;
        if(l2==null) return l1;
        if(l1.val<l2.val){
            l1.next=merge(l1.next,l2);
            return l1;
        }else{
            l2.next=merge(l1,l2.next);
            return l2;
        }
    }

提交代码之后:

Runtime: 3 ms, faster than 92.98% of Java online submissions for Merge k Sorted Lists.

Memory Usage: 41.6 MB, less than 12.34% of Java online submissions for Merge k Sorted Lists.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值