标签:
题目:
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) {
int k = lists.size();
if(k==0)return null;
PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(
k, new Comparator<ListNode>(){
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val-o2.val;
}
});
for(int i=0; i<k; i++){
ListNode node = lists.get(i);
if(node != null){
heap.offer(node);
}
}
ListNode head = new ListNode(0), pre = head;
while(heap.size()>0){
ListNode c = heap.poll();
pre.next = c;
pre = pre.next;
if(c.next != null)
heap.offer(c.next);
}
return head.next;
}
}标签:
原文地址:http://blog.csdn.net/allhaillouis/article/details/44160175