23. Merge k Sorted Lists

题目

原始地址:https://leetcode.com/problems/merge-k-sorted-lists/#/description

/**
 * 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) {
        
    }
}

描述

合并k个有序链表为一个有序链表。

分析

多路归并问题。基本的思路是新建一个链表头,我们需要维护一个容器,开始把这k个链表的头节点放到这个容器冲,每次在容器中挑选一个最小的接到新链表之后,并且把这个节点的后续节点补充到容器中,直到结束。
什么数据结构最合适呢?要求不一定整体有序但是能取到最小值,而且删除和插入元素的效率要比较高。当然最合适的就是最小堆了,java中对应的类是PriorityQueue。
另外需要注意,由于ListNode未实现Comparable接口,如果要使用PriorityQueue,需要传入一个Comparator,并且根据val值来进行比较。

解法

/**
 * 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 == null || lists.length == 0) {
            return null;
        }
        PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
            public int compare(ListNode l, ListNode r) {
                return l.val - r.val;
            }
        });
        for (ListNode ln : lists) {
            if (ln != null) {
                queue.offer(ln);
            }
        }
        ListNode head = new ListNode(0), node = head, tmp;
        while (queue.size() > 0) {
            tmp = queue.poll();
            if (tmp.next != null) {
                queue.offer(tmp.next);
            }
            node.next = tmp;
            node = node.next;
        }
        return head.next;
    }
}
posted @ 2017-05-09 20:39  北冥尝有鱼  阅读(140)  评论(0编辑  收藏  举报