leetcode--Merge k Sorted Lists

来源:互联网 发布:当程序员好吗 编辑:程序博客网 时间:2024/06/14 16:56

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

[java] view plain copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public ListNode mergeKLists(ListNode[] lists) {  
  11.         Queue<ListNode> heap = new PriorityQueue<ListNode>(new Comparator<ListNode>(){  
  12.             @Override public int compare(ListNode l1, ListNode l2) {   
  13.                 return l1.val - l2.val;   
  14.             }  
  15.         });  
  16.         ListNode head = new ListNode(0), tail = head;  
  17.         for (ListNode node : lists) if (node != null) heap.offer(node);  
  18.         while (!heap.isEmpty()) {  
  19.             tail.next = heap.poll();//获取最大值  
  20.             tail = tail.next;  
  21.             if (tail.next != null) heap.offer(tail.next);  
  22.         }  
  23.         return head.next;  
  24.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/45581225

原创粉丝点击