码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Merge k Sorted Lists

时间:2014-12-27 00:09:07      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

LeetCode Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4187685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!