23. Merge k Sorted Lists
Last updated
Last updated
/**
* 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; // notice this!
return partition(lists, 0, lists.length - 1);
}
private ListNode partition(ListNode[] lists, int s, int e) {
if (s == e) {
return lists[s]; // notice this!
} else if (s < e) {
int mid = (s+e)/2;
ListNode l1 = partition(lists, s, mid);
ListNode l2 = partition(lists, mid+1, e);
return merge(l1, l2);
} else {
return null; // notice this!
}
}
// this part is leetcode 21. Merge Two Sorted Lists
private ListNode merge(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1); // notice this should new a node
ListNode pre = head;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
pre.next = l1;
l1 = l1.next;
} else {
pre.next = l2;
l2 = l2.next;
}
pre = pre.next;
}
pre.next = (l1 == null) ? l2 : l1;
return head.next;
}
} private ListNode partition(ListNode[] lists, int s, int e) {
if (s == e) {
return lists[s]; // notice this!
} else if (s < e) {
int mid = (s+e)/2;
ListNode l1 = partition(lists, s, mid);
ListNode l2 = partition(lists, mid+1, e);
return merge(l1, l2);
} else {
return null; // notice this!
}
}/**
* 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;
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, (a, b) -> a.val - b.val);
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
for (ListNode list : lists) {
if (list != null) {
queue.add(list);
}
}
while (!queue.isEmpty()) {
cur.next = queue.poll();
cur = cur.next;
if (cur.next != null) {
queue.add(cur.next);
}
}
return dummy.next;
}
}