Merge k Sorted Lists
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null. Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null. /**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// using a min heap
if (lists == null || lists.size() == 0) return null;
PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.size(), new Comparator<ListNode>(){
@Override
public int compare(ListNode node1, ListNode node2) {
return node1.val - node2.val;
}
});
for (ListNode node : lists) {
if (node != null) {
pq.offer(node);
}
}
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (! pq.isEmpty()) {
ListNode currMin = pq.poll();
if (currMin.next != null) {
pq.offer(currMin.next);
}
curr.next = new ListNode(currMin.val);
curr = curr.next;
}
return dummy.next;
}
} # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
dummy = ListNode(0)
curr = dummy
# 维持min heap,就可以跟踪剩余node中的最小值
pq = []
for head in lists:
if head:
heapq.heappush(pq, (head.val, head))
while pq:
node = heapq.heappop(pq)[1]
if node.next:
heapq.heappush(pq, (node.next.val, node.next))
curr.next = ListNode(node.val)
curr = curr.next
return dummy.nextclass Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) return null;
return mergeSort(lists, 0, lists.length - 1);
}
private ListNode mergeSort(ListNode[] lists, int start, int end) {
if (start == end) return lists[start];
int mid = (start + end) / 2;
ListNode head1 = mergeSort(lists, start, mid);
ListNode head2 = mergeSort(lists, mid + 1, end);
return merge(head1, head2);
}
private ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (head1 != null || head2 != null) {
if (head1 == null) {
curr.next = head2;
return dummy.next;
} else if (head2 == null) {
curr.next = head1;
return dummy.next;
} else if (head1.val < head2.val) {
curr.next = head1;
head1 = head1.next;
curr.next.next = null;
curr = curr.next;
} else {
curr.next = head2;
head2 = head2.next;
curr.next.next = null;
curr = curr.next;
}
}
return dummy.next;
}
}