23. Merge k Sorted Lists

来源:互联网 发布:苹果5s蜂窝数据打不开 编辑:程序博客网 时间:2024/06/03 22:41

题目

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

题解

将k个有序链表重新排序,这里涉及到k个链表的排序,可以使用有序队列解决。

代码

/** * 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<ListNode>(lists.length,new Comparator<ListNode>(){            @Override            public int compare(ListNode o1,ListNode o2){                if (o1.val<o2.val)                    return -1;                else if (o1.val==o2.val)                    return 0;                else                     return 1;            }        });                ListNode dummy = new ListNode(0);        ListNode tail=dummy;                for (ListNode node:lists)            if (node!=null)                queue.add(node);                    while (!queue.isEmpty()){            tail.next=queue.poll();            tail=tail.next;                        if (tail.next!=null)                queue.add(tail.next);        }        return dummy.next;    }}


原创粉丝点击