• (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
  • 相关阅读:
    set用法
    01分数规划
    unique && stl的全排列
    lower_bound() && upper_bound()
    spfa判负环
    倍增求LCA
    数据生成c++程序模板
    samba
    vsftp快速配置
    grub丢失的修复
  • 原文地址:https://www.cnblogs.com/hansongjiang/p/3847638.html
Copyright © 2020-2023  润新知