Merge k Sorted Lists

 1 /* Min heap*/
 2 public class Solution {
 3     public ListNode mergeKLists(ArrayList<ListNode> lists) {
 4         if(lists.size()<=0) return null;
 5         
 6         Comparator<ListNode> comparator = new Comparator<ListNode>(){
 7             public int compare(ListNode m,ListNode n){
 8                 return m.val-n.val;
 9             }
10         };
11         PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.size(),comparator);
12         for(int i=0;i<lists.size();i++){
13             if(lists.get(i)!=null){
14                 pq.add(lists.get(i));
15             }
16         }
17         ListNode safe = new ListNode(-1);
18         ListNode pre = safe;
19         while(!pq.isEmpty()){
20             pre.next = pq.poll();
21             pre = pre.next;
22             if(pre.next!=null)
23                 pq.add(pre.next);
24         }
25         return safe.next;
26     }
27 }
View Code

 

posted @ 2014-02-06 05:37  krunning  阅读(101)  评论(0编辑  收藏  举报