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(ArrayList<ListNode> lists) {
if(lists==null || lists.size()==0) {
return null;
}
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>(){
public int compare(ListNode a, ListNode b) {
return a.val>b.val?1:(a.val==b.val?0:-1);
}
}
);
for(int i=0;i<lists.size();i++) {
if(lists.get(i)!=null) {
queue.add(lists.get(i));
}
}
ListNode head = new ListNode(0);
ListNode cur = head;
while(queue.size()!=0) {
cur.next = queue.poll();
if(cur.next.next!=null) {
queue.add(cur.next.next);
}
cur = cur.next;
}
return head.next;
}
}
没有评论:
发表评论