zoukankan      html  css  js  c++  java
  • Merge k Sorted Lists

    use PriorityQueue( Priority Heap)

    the time complexity will be O(k * lgn)

     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(ArrayList<ListNode> lists) {
    14         // IMPORTANT: Please reset any member data you declared, as
    15         // the same Solution instance will be reused for each test case.
    16         if(lists == null)
    17             return null;
    18         if(lists.size() == 0)
    19             return null;
    20         if(lists.size() == 1)
    21             return lists.get(0);
    22             
    23         Comparator<ListNode> mycomparator = new Comparator<ListNode>(){
    24             public int compare(ListNode m, ListNode n){  
    25                 if(m.val==n.val) return 0;  
    26                 else if(m.val>n.val) return 1;  
    27                 return -1;  
    28             }  
    29         } ;
    30         PriorityQueue<ListNode> myheap = new PriorityQueue<ListNode>(lists.size(), mycomparator);
    31         
    32         for(ListNode i:lists)
    33         {
    34             if(i != null)
    35                 myheap.add(i);
    36         }
    37         
    38         ListNode head = null;
    39         ListNode tmp = head;
    40         
    41         while(!myheap.isEmpty())
    42         {
    43             ListNode out = myheap.poll();
    44             if(head == null)
    45             {
    46                 head = out;
    47                 tmp = head;
    48             }
    49             else
    50             {
    51                 tmp.next = out;
    52                 tmp = tmp.next;
    53             }
    54             if(out.next != null)
    55                 myheap.add(out.next);
    56         }
    57         return head;
    58     }
    59 }
  • 相关阅读:
    [POJ1724]ROADS
    表达式求值
    [NOIp2017提高组]奶酪(BFS)
    [NOIp2012提高组]Vigenère 密码
    [NOIp2012提高组]国王游戏
    [POJ1321]棋盘问题
    [POJ3009]Curling2.0
    垃圾陷阱
    2019CSP day1t2 括号树
    2019CSP游记
  • 原文地址:https://www.cnblogs.com/jasonC/p/3407819.html
Copyright © 2011-2022 走看看