leetcode23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Subscribe to see which companies asked this question.

解题思路:
要给k个顺序单链表排序,我们熟知合并两个顺序单链表的操作。但是这里是k个,简单的想:先两个合并,再拿合并的和第三个合并,这样子的每次都会重复遍历前一次合并过的链表,这样重复率太高了,不合适。
于是,就想要尽可能的减少重复遍历的数量,这时候就想到用递归不断二分,合并。

//Arrays.copyOfRange  拷贝数组,from指向开始的下标,to表示结束的后一个下标
    public static ListNode mergeKLists(ListNode[] lists) {

        if (lists.length == 0)
            return null;
        if (lists.length == 1)
            return lists[0];

        ListNode left,right;
        left = mergeKLists(Arrays.copyOfRange(lists,0,lists.length/2));
        right =mergeKLists(Arrays.copyOfRange(lists,lists.length/2,lists.length));
        return mergeTwoLists(left,right);
    }

    public static 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;
        }

    }

If someone understand how priority queue works, then it would be trivial to walk through the codes.
My question: is that possible to solve this question under the same time complexity without implementing the priority queue?

public class Solution {
    public ListNode mergeKLists(List<ListNode> lists) {
        if (lists==null||lists.size()==0) return null;

        PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
            @Override
            public int compare(ListNode o1,ListNode o2){
                if (o1.val<o2.val)
                    return -1;
                else if (o1.val==o2.val)
                    return 0;
                else 
                    return 1;
            }
        });

        ListNode dummy = new ListNode(0);
        ListNode tail=dummy;

        for (ListNode node:lists)
            if (node!=null)
                queue.add(node);

        while (!queue.isEmpty()){
            tail.next=queue.poll();
            tail=tail.next;

            if (tail.next!=null)
                queue.add(tail.next);
        }
        return dummy.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值