• 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 }
  • 相关阅读:
    Python基础四
    Python基础三
    Python基础二
    Python基础一
    JAVA测试
    国庆随笔
    ATM-JAVA程序 //程序有5处相同错误,找不出原因 转账功能没有实现,修改密码来不及实现了
    JAVA程序测试感受
    第八周
    第七周
  • 原文地址:https://www.cnblogs.com/jasonC/p/3407819.html
Copyright © 2020-2023  润新知