23. Merge k Sorted Lists

一、题目

  1、审题

    

  2、分析

    将 n 个有序链表合并成为一个有序链表。

 

二、解答

  1、思路:

  Java 有一个 PriorityQueue,该队列能够将放入的对象进行排序。故将所有非空队头元素放入该队列,取出一个元素后,再放入所取出元素指向的下一个非空结点;当队列中元素为空时,取出的顺序即为排序后的新的链表的元素顺序。

  有关 PriorityQueue:

    add(E e)    添加元素
    clear() 清空
    contains(Object o) 检查是否包含当前参数元素
    offer(E e) 添加元素
    peek() 读取元素,(不删除)
    poll() 取出元素,(删除)
    remove(Object o) 删除指定元素
    size() 返回长度
  
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {

        if(lists == null || lists.length == 0)
            return null;

        /*
         *  PriorityQueue:    自动根据优先级排序的队列
         */
        PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(10, new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });

        for (int i = 0; i < lists.length; i++)
            if(lists[i] != null)
                heap.offer(lists[i]);   // add

        ListNode head = null;
        ListNode pre = head;
        while(heap.size() > 0) {
            ListNode cur = heap.poll();     // 取出,删除
            if(head == null)
                head = cur;
            else
                pre.next = cur;

            pre = cur;
            if(cur.next != null)
                heap.offer(cur.next);   //add
        }
        return  head;
    }
}

 

posted @ 2018-08-04 09:30  skillking2  阅读(142)  评论(0编辑  收藏  举报