🌗 23. 合并K个升序链表
2022年10月10日
- algorithm
🌗 23. 合并K个升序链表
难度: 🌗
问题描述
解法
/**
* 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) {
// 思路:
// 先分治,后两两合并
int len = lists.length;
// 特殊情况特判
if(len == 0) {
return null;
}
if(len == 1) {
return lists[0];
}
// len > 1
return mySol(lists, 0, len - 1);
}
private ListNode mySol(ListNode[] lists, int left, int right) {
// 递归终止条件
if(left >= right) {
return lists[left];
}
// left < right
int mid = left + ((right - left) >> 1);
ListNode a = mySol(lists, left, mid);
ListNode b = mySol(lists, mid + 1, right);
return merge(a, b);
}
private ListNode merge(ListNode a, ListNode b) {
if(a == null) {
return b;
}
if(b == null) {
return a;
}
ListNode res = new ListNode(-1);
ListNode cur = res;
while(a != null && b != null) {
if(a.val <= b.val) {
cur.next = a;
cur = cur.next;
a = a.next;
} else {
cur.next = b;
cur = cur.next;
b = b.next;
}
}
while(a != null) {
cur.next = a;
a = a.next;
cur = cur.next;
}
while(b != null) {
cur.next = b;
cur = cur.next;
b = b.next;
}
return res.next;
}
}