JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  174 随笔 :: 0 文章 :: 0 评论 :: 30090 阅读

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 }
复制代码

 

 

 

posted on   JasonChang  阅读(190)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
点击右上角即可分享
微信分享提示