Merge k Sorted Lists

https://leetcode.com/problems/merge-k-sorted-lists/description/

Merge k sorted linked lists and return it as one sorted list.

Analyze and describe its complexity.

Thoughts

每次遍历找范围内最小,用min heap。每次找到最小pop后再把最小的next push进去作为候选。C++的pq 用greater作为comparator才是min heap,和Java的相反。。

Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                pq.offer(lists[i]);    
            }
        }

        ListNode dummy = new ListNode(0), node = dummy;

        while (!pq.isEmpty()) {
            ListNode newNode = pq.poll();
            node.next = newNode;
            node = newNode;
            if (newNode.next != null) {
                pq.offer(newNode.next);
            }
        } 

        return dummy.next;
    }
}

Aanlysis

TC: O(nlgn)

Last updated

Was this helpful?