Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
My code:
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> queue = new PriorityQueue<>((a,b)->a.val-b.val);
int k = lists.length;
for(int i=0; i<k; i++){
if(lists[i]!=null) queue.offer(lists[i]);
}
ListNode dummy = new ListNode(0);
ListNode cur = null;
cur = dummy;
while(!queue.isEmpty()){
cur.next = queue.poll();
cur = cur.next;
if(cur.next!=null){
queue.offer(cur.next);
}
}
return dummy.next;
}
}
总结:完美,学了lambda表达式,现学现卖。用了进去很好用呀。
另外一种重载方式:
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
@Override
public int compare(ListNode o1,ListNode o2){
if (o1.val<o2.val)
return -1;
else if (o1.val==o2.val)
return 0;
else
return 1;
}
});