JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

use PriorityQueue( Priority Heap)

the time complexity will be O(k * lgn)

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode mergeKLists(ArrayList<ListNode> lists) {
14         // IMPORTANT: Please reset any member data you declared, as
15         // the same Solution instance will be reused for each test case.
16         if(lists == null)
17             return null;
18         if(lists.size() == 0)
19             return null;
20         if(lists.size() == 1)
21             return lists.get(0);
22             
23         Comparator<ListNode> mycomparator = new Comparator<ListNode>(){
24             public int compare(ListNode m, ListNode n){  
25                 if(m.val==n.val) return 0;  
26                 else if(m.val>n.val) return 1;  
27                 return -1;  
28             }  
29         } ;
30         PriorityQueue<ListNode> myheap = new PriorityQueue<ListNode>(lists.size(), mycomparator);
31         
32         for(ListNode i:lists)
33         {
34             if(i != null)
35                 myheap.add(i);
36         }
37         
38         ListNode head = null;
39         ListNode tmp = head;
40         
41         while(!myheap.isEmpty())
42         {
43             ListNode out = myheap.poll();
44             if(head == null)
45             {
46                 head = out;
47                 tmp = head;
48             }
49             else
50             {
51                 tmp.next = out;
52                 tmp = tmp.next;
53             }
54             if(out.next != null)
55                 myheap.add(out.next);
56         }
57         return head;
58     }
59 }

 

 

 

posted on 2013-11-05 07:02  JasonChang  阅读(189)  评论(0编辑  收藏  举报