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; } * } */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists){
        if(lists.length == 0)
            return null;
        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        for(ListNode temp : lists){
            if(temp != null)
                queue.add(temp);
        }
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        dummy.next = null;
        while(!queue.isEmpty()){
            ListNode min = queue.poll();
            cur.next = min;
            cur = min;
            if(min.next != null)
                queue.add(min.next);
        }
        return dummy.next;
    }
}

你可能感兴趣的:(合并)