leetcode--Merge k Sorted Lists

来源:互联网 发布:软件测试linux面试题 编辑:程序博客网 时间:2024/06/13 17:59
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) {Queue<ListNode> heap = new PriorityQueue<ListNode>(new Comparator<ListNode>(){            @Override public int compare(ListNode l1, ListNode l2) {                 return l1.val - l2.val;             }        });ListNode head = new ListNode(0), tail = head;        for (ListNode node : lists) if (node != null) heap.offer(node);        while (!heap.isEmpty()) {            tail.next = heap.poll();//获取最大值            tail = tail.next;            if (tail.next != null) heap.offer(tail.next);        }        return head.next;    }}

0 0