题解 | 合并k个已排序的链表
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
基于合并两个已排序的链表,将k个已排序的链表不断的划分为2组,直到划分成2个或1个链表为止
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类ArrayList
* @return ListNode类
*/
public ListNode mergeKLists (ArrayList<ListNode> lists) {
// write code here
int n = lists.size();
if(n == 0) return null;
if(n == 2) return Merge(lists.get(0), lists.get(1));
else if(n == 1) return lists.get(0);
else {
int half = n / 2; // 分治
ListNode left = mergeKLists(new ArrayList(lists.subList(0, half))); // subList的参数遵循左闭右开的原则
ListNode right = mergeKLists(new ArrayList(lists.subList(half, n)));
return Merge(left, right);
}
}
/**
* 合并两个已排序的链表
*/
public static ListNode Merge(ListNode phead1, ListNode phead2) {
ListNode dummy = new ListNode(-1);
ListNode head = dummy;
while(phead1 != null && phead2 != null) {
if(phead1.val <= phead2.val) {
head.next = phead1;
phead1 = phead1.next;
} else {
head.next = phead2;
phead2 = phead2.next;
}
head = head.next;
}
if(phead1 == null) head.next = phead2;
if(phead2 == null) head.next = phead1;
return dummy.next;
}
}

查看11道真题和解析