Wednesday, January 7, 2015

LeetCode 23: Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeKLists(List<ListNode> lists) {
        if (lists.size() == 0)
            return null;
            
        // Adopt priority queue
        PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.size(),
				new Comparator<ListNode>()
				{
					public int compare(ListNode a, ListNode b)
					{
						if (a.val > b.val)
							return 1;
						else if (a.val < b.val)
							return -1;
						else 
							return 0;
					}
				});
        
	// Add first node of each list to the queue
	for (ListNode list : lists)
		if (list != null)
			pq.offer(list);
 
	ListNode helper = new ListNode(0);
	ListNode node = helper;
 
	while (pq.size() > 0)
	{
		// poll() retrieves and removes the minimum node of 'pq'
		ListNode temp = pq.poll();
			
		node.next = temp;
 
		// Keep adding next node of removed minimum node 'temp'
		if (temp.next != null)
		pq.offer(temp.next);
 
		node = node.next;
	}
 
	return helper.next;
    }
}

No comments:

Post a Comment