今天又学了一招优先队列
队列中的元素的排序规则由我们自定义
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null||lists.length==0){
return null;
}
ListNode yummy = new ListNode(0);
ListNode ans =yummy;
PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(new Comparator<ListNode>() {
@Override
public int compare(ListNode l1, ListNode l2) {
return l1.val - l2.val;
}
});
if(lists ==null ||lists.length==0) return null;
for(ListNode list:lists){
if(list!=null)
priorityQueue.add(list);
}
while (!priorityQueue.isEmpty()){
ListNode first = priorityQueue.poll();
yummy.next = first;
yummy=yummy.next;
if(first.next!=null)
priorityQueue.add(first.next);
}
return ans.next;
}
}
方法二:
也是通过了
两两合并汇总到大的链表上
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode ans = null;
for(int i = 0; i< lists.length;i++){
if(lists[i]==null ) continue;
ans=merge(ans,lists[i]);
}
return ans;
}
public static ListNode merge(ListNode list1 , ListNode list2){
if(list1 == null || list2 == null){
return list1==null? list2:list1;
}
ListNode a = list1;
ListNode b = list2;
ListNode temp = new ListNode(0);
ListNode head = temp;
while(a!=null && b!=null){
if(a.val<b.val){
temp.next = a;
a=a.next;
}else{
temp.next = b;
b= b.next;
}
temp = temp.next;
}
temp.next = a==null?b:a;
return head.next;
}
}