您的位置:首页 > 其它

leetcode--Merge k Sorted Lists

2017-08-08 09:00 106 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

[java] view
plain copy

/** 

 * Definition for singly-linked list. 

 * public class ListNode { 

 *     i
4000
nt 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;  

    }  



原文链接http://blog.csdn.net/crazy__chen/article/details/45581225
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: