版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/86921737
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
优先队列
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> p = new PriorityQueue<>(new Comparator<ListNode>(){//复习时候多看看,不熟练
@Override
public int compare(ListNode n1, ListNode n2){
if (n1.val < n2.val) return -1;
else if (n1.val == n2.val) return 0;
else return 1;
}
});
ListNode ans = new ListNode(0), tail = ans;
for (ListNode o : lists)
if (o != null) p.offer(o);
while (!p.isEmpty()){
ListNode t = p.poll();
tail.next = t;
tail = tail.next;
if (t.next != null) p.offer(t.next);
}
return ans.next;
}
}