LeetCode23 – Merge k Sorted Lists (Java)

来源:互联网 发布:java怎么求质数 编辑:程序博客网 时间:2024/06/09 21:11
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.


Analysis


The simplest solution is using PriorityQueue. The elements of the priority queue are ordered according to their natural ordering, or by a comparator provided at the construction time (in this case).


Java Solution

public ListNode mergeKLists(ListNode[] lists) {    if(lists==null||lists.length==0)        return null;     PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(new Comparator<ListNode>(){        public int compare(ListNode l1, ListNode l2){            return l1.val - l2.val;        }    });     ListNode head = new ListNode(0);    ListNode p = head;    for(ListNode list: lists){        if(list!=null)            queue.offer(list);    }         while(!queue.isEmpty()){        ListNode n = queue.poll();        p.next = n;        p=p.next;         if(n.next!=null)            queue.offer(n.next);    }         return head.next; }


0 0
原创粉丝点击