剑指offer25 合并两个排序的链表
方法一:递归
public ListNode Merge(ListNode l1,ListNode l2) {
if(l1==null||l2==null){
return l1!=null?l1:l2;
}
if(l1.val<=l2.val){
l1.next=Merge(l1.next,l2);
return l1;//递归算法参考由下至上的原则
}
else {
l2.next=Merge(l1,l2.next);
return l2;
}
}
方法二:迭代
public ListNode mergeTwoLists(ListNode l1,ListNode l2) {
ListNode list=new ListNode(0);
ListNode node=list;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
node.next=l1;
l1=l1.next;
}
else {
node.next=l2;
l2=l2.next;
}
node=node.next;
}
node.next=l1!=null?l1:l2;
return list.next;
}
力扣23 合并K个生序链表
方法一:优先队列(小顶堆)
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null||lists.length==0) return null;
PriorityQueue<ListNode> queue=new PriorityQueue<>(lists.length, 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;
}
});
ListNode node=new ListNode(0);
ListNode cur=node;
for(ListNode list:lists){
if(list!=null) {
queue.add(list);
}
}
while(!queue.isEmpty()){
ListNode nextNode=queue.poll();
cur.next=nextNode;
cur=cur.next;
if(nextNode.next!=null){
queue.add(nextNode.next);//每次取的都是首结点,需要判断当前list是否还有结点
}
}
return node.next;
}
方法二:分治
思路和剑指offer25一致,只看局部两个链表,把两个链表合并。
分:把若干个链表两两划分(划分的套路就是取最左和最右,取中间值,然后递归,(最左,中间)和(中间+1,最右))
合:把上一步所得的链表两两合并
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
return merge(lists, 0, lists.length - 1);
}
private ListNode merge(ListNode[] lists, int left, int right) {
if (left == right) return lists[left];
int mid = left + (right - left) / 2;
ListNode l1 = merge(lists, left, mid);
ListNode l2 = merge(lists, mid + 1, right);
return mergeTwoLists(l1, l2);
}
private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}