Merge k Sorted Lists

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

Merge k Sorted Lists

上一篇:克隆Wheekling——兴起


下一篇:SQL Server 常用日期查询语句