首页 > 其他 > 详细

Merge k Sorted Lists

时间:2014-02-06 12:38:37      阅读:354      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 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

原文:http://www.cnblogs.com/krunning/p/3538589.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!