码迷,mamicode.com
首页 > 其他好文 > 详细

23. Merge k Sorted Lists

时间:2017-07-28 15:42:05      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:[]   ref   matrix   err   ==   new   val   panda   des   

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

378. Kth Smallest Element in a Sorted Matrix

/**
 * 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){
                
                    return o1.val - o2.val;
            }
        });
        
        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;
    }
}

  

23. Merge k Sorted Lists

标签:[]   ref   matrix   err   ==   new   val   panda   des   

原文地址:http://www.cnblogs.com/apanda009/p/7250270.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!