优秀算法:
1、题目简介:
/** * 给你一个链表数组,每个链表都已经按升序排列。 * * 请你将所有链表合并到一个升序链表中,返回合并后的链表。 * 示例 1: * * 输入:lists = [[1,4,5],[2,3,4],[5,6]] * 输出:[1,2,3,4,4,5,5,6] * 解释:链表数组如下: * [ * 1->4->5, * 2->3->4, * 5->6 * ] * 将它们合并到一个有序链表中得到。 * 1->2->3->4->4->5->5->6 */
2、解题思路:
采用小顶堆思想,每次都是弹出最小的,然后放到链表里。
3、核心代码演示:
public class MergeNodeLists {
public static void main(String[] args) {
int[] a = {1,4,5};
int[] b = {2,3,4};
int[] c = {5,6};
ListNode nodeA = createNode(a);
ListNode nodeB = createNode(b);
ListNode nodeC = createNode(c);
ListNode[] lists = {nodeC,nodeA,nodeB};
//ListNode node = mergeKLists(lists);
ListNode node = mergeKLists1(lists);
while (node != null){
System.out.print(node.val + " ");
node = node.next;
}
System.out.println();
}
//创建链表
private static ListNode createNode(int[] a) {
ListNode head = new ListNode();
head.val = a[0];
ListNode cur = head;
for(int i = 1;i < a.length;i++){
ListNode node = new ListNode();
node.val = a[i];
cur.next = node;
cur = cur.next;
}
return head;
}
public static class ListNode {
public int val;
public ListNode next;
}
//指定比较器comparator
public static class ListNodeComparator implements Comparator<ListNode> {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
}
//合并多个链表
public static ListNode mergeKLists(ListNode[] lists) {
if (lists == null) {
return null;
}
//https://blog.csdn.net/u010853261/article/details/78520960 小顶堆。小堆堆要求根节点的关键字既小于或等于左子树的关键字值,又小于或等于右子树的关键字值。
PriorityQueue<ListNode> heap = new PriorityQueue<>(new ListNodeComparator());
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) {
heap.add(lists[i]);
}
}
if (heap.isEmpty()) {
return null;
}
ListNode head = heap.poll();
ListNode pre = head;
if (pre.next != null) {
heap.add(pre.next);
}
while (!heap.isEmpty()) {
ListNode cur = heap.poll();
pre.next = cur;
pre = cur;
if (cur.next != null) {
heap.add(cur.next);
}
}
return head;
}
}
这是其中一个思路分享,大家一定学会举一反三,多多练习!