您的位置:首页 > 其它

LeetCode Merge k Sorted Lists

2014-12-26 23:16 253 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
if (lists == null || lists.size() == 0) {
return null;
}
Comparator<ListNode> compare=new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
};

PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.size(), compare);
for (ListNode node : lists) {
if (node != null) {
queue.add(node);
}
}
ListNode ret = new ListNode(0);
ListNode temp = ret;
while (!queue.isEmpty()) {
temp.next=queue.poll();
temp=temp.next;
if (temp.next != null) {
queue.add(temp.next);
}
}
return ret.next;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: