LeetCode Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 

 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(List<ListNode> lists) {
14         if (lists == null || lists.size() == 0) {
15             return null;
16         }
17         Comparator<ListNode> compare=new Comparator<ListNode>() {
18             @Override
19             public int compare(ListNode o1, ListNode o2) {
20                 return o1.val - o2.val;
21             }
22         };
23 
24         PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.size(), compare);
25         for (ListNode node : lists) {
26             if (node != null) {
27                 queue.add(node);
28             }
29         }
30         ListNode ret = new ListNode(0);
31         ListNode temp = ret;
32         while (!queue.isEmpty()) {
33             temp.next=queue.poll();
34             temp=temp.next;
35             if (temp.next != null) {
36                 queue.add(temp.next);
37             }
38         }
39         return ret.next;
40     } 
41     
42 }

 

posted @ 2014-12-26 23:16  birdhack  阅读(111)  评论(0编辑  收藏  举报