zoukankan      html  css  js  c++  java
  • (java) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode mergeKLists(List<ListNode> lists) {
    14         ListNode head=new ListNode(-1);
    15         ListNode tail=head;
    16         if(lists.size()<=0) return null;
    17         Comparator<ListNode> mycmp=new Comparator<ListNode>()
    18         {
    19             public int compare(ListNode l1,ListNode l2)
    20             {
    21                 if(l1.val>l2.val) return 1;
    22                 else if(l1.val<l2.val)return -1;
    23                 return 0;
    24                 
    25                 
    26                 
    27             }
    28             
    29         } ;
    30         
    31         PriorityQueue<ListNode> prq=new PriorityQueue<ListNode>(lists.size(),mycmp);
    32         for(ListNode n:lists)
    33         {
    34             if(n!=null)
    35             {
    36                 prq.add(n);
    37             }
    38             
    39         }
    40         while(prq.size()>0)
    41         {
    42             ListNode tem=prq.poll();
    43             tail.next=tem;
    44             tail=tail.next;
    45             if(tem.next!=null)
    46             {
    47                 prq.add(tem.next);
    48             }
    49     
    50             
    51         }
    52         
    53             return head.next;
    54         
    55         
    56         
    57         
    58         
    59     }
    60 }
    View Code
  • 相关阅读:
    Web前端学习笔记之BootStrap
    js 闭包解决方案
    函数节流简要解析
    js 观察者模式
    arguments解析
    js 职责链模式简要介绍
    js 工厂模式简要介绍
    jsonp跨域总结
    算法复杂度
    正则表达式的$
  • 原文地址:https://www.cnblogs.com/hansongjiang/p/3847638.html
Copyright © 2011-2022 走看看