67 lines
1.7 KiB
Java
67 lines
1.7 KiB
Java
/*
|
|
* @lc app=leetcode id=23 lang=java
|
|
*
|
|
* [23] Merge k Sorted Lists
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* 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) {
|
|
if(lists == null || lists.length == 0) {
|
|
return null;
|
|
}
|
|
return mergeRecursively(lists, 0, lists.length-1);
|
|
}
|
|
|
|
private ListNode mergeRecursively(ListNode[] lists, int i, int j) {
|
|
if (i > j) {
|
|
return null;
|
|
}else if(i == j) {
|
|
return lists[i];
|
|
} else if (j - i == 1) {
|
|
return merge(lists[i], lists[j]);
|
|
}
|
|
int m = (i+j)/2;
|
|
return merge(mergeRecursively(lists, i, m), mergeRecursively(lists, m+1, j));
|
|
}
|
|
|
|
private ListNode merge(ListNode l1, ListNode l2) {
|
|
ListNode dummy = new ListNode(0), tail = dummy;
|
|
dummy.next = null;
|
|
while(l1 != null || l2 != null) {
|
|
if(l1 == null || l2 == null) {
|
|
if(l1 != null) {
|
|
tail.next = l1;
|
|
} else if(l2 != null) {
|
|
tail.next = l2;
|
|
}
|
|
break;
|
|
}
|
|
if(l1.val <= l2.val) {
|
|
tail.next = l1;
|
|
l1 = l1.next;
|
|
tail = tail.next;
|
|
tail.next = null;
|
|
} else {
|
|
tail.next = l2;
|
|
l2 = l2.next;
|
|
tail = tail.next;
|
|
tail.next = null;
|
|
}
|
|
}
|
|
return dummy.next;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|