Merge k Sorted Lists

来源:互联网 发布:淘宝微淘粉丝怎么看 编辑:程序博客网 时间:2024/06/05 20:12

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

Analyze and describe its complexity.

Example

Given lists:

[  2->4->null,  null,  -1->null],

return -1->2->4->null.

该题目使用heap的方法去做,首先将lists中的所用节点放到heap中,然后分别将listnode中的节点向后移动,直到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) {          // write your code here        if (lists == null || lists.size() == 0) {            return null;        }        Comparator<ListNode> cmp = new Comparator<ListNode>() {            public int compare(ListNode a, ListNode b) {                return a.val - b.val;            }        };        Queue<ListNode> pq = new PriorityQueue<>(lists.size(), cmp);        for (int i = 0; i < lists.size(); i++) {            if (lists.get(i) != null) {                pq.offer(lists.get(i));            }        }        ListNode dummy = new ListNode(-1);        ListNode head = dummy;        ListNode node = null;        while (!pq.isEmpty()) {            node = pq.poll();            head.next = node;            head = head.next;            if (node.next != null) {                pq.offer(node.next);            }        }        return dummy.next;    }}