给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
提示:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4
解题思路:
最笨的方法是,每次比对各个链表头节点,取出最小的值,放入结果链表,其实,可以采用归并的思路,对链表节点进行排序,再合并。
package com.alibaba.study.leetcode;
import java.util.Arrays;
/**
* @Auther: wjj
* @Date: 2020/12/11 15:14
* @Description:
*/
public class LeetCode23 {
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1, null);
ListNode listNode2 = new ListNode(2, null);
ListNode listNode3 = new ListNode(3, null);
ListNode listNode4 = new ListNode(1, null);
ListNode listNode5 = new ListNode(4, null);
ListNode listNode6 = new ListNode(6, null);
ListNode listNode7 = new ListNode(5, null);
listNode1.next = listNode2;
listNode2.next = listNode3;
listNode4.next = listNode5;
listNode5.next = listNode6;
ListNode node = mergeKLists(new ListNode[]{listNode1, listNode4, listNode7});
System.out.printf("结果:" + node.toString());
}
public static ListNode mergeKLists(ListNode[] lists) {
return mergeSort(lists);
}
private static ListNode mergeSort(ListNode[] lists){
int len = lists.length;
if(len == 0){
return null;
}
if(len < 2){
return lists[0];
}
ListNode[] left = Arrays.copyOfRange(lists, 0, len/2);
ListNode[] right = Arrays.copyOfRange(lists, len/2, len);
ListNode merge = merge(mergeSort(left), mergeSort(right));
return merge;
}
private static ListNode merge(ListNode left, ListNode right){
if(left == null){
return right;
}
if(right == null){
return left;
}
ListNode node = null;
if(left.val < right.val){
node = new ListNode(left.val, null);
left = left.next;
} else {
node = new ListNode(right.val, null);
right = right.next;
}
ListNode head = node;
while (left != null && right != null){
if(left.val < right.val){
node.next = new ListNode(left.val, null);
left = left.next;
} else {
node.next = new ListNode(right.val, null);
right = right.next;
}
node = node.next;
}
while (left!= null){
node.next = left;
left = left.next;
node = node.next;
}
while (right!= null){
node.next = right;
right = right.next;
node = node.next;
}
return head;
}
}
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
@Override
public String toString() {
ListNode node = next;
StringBuilder sb = new StringBuilder();
sb.append(val + "->");
while (node != null){
sb.append(node.val + "->");
node = node.next;
}
return sb.toString();
}
}