合并k个排序链表
2016-07-12 16:02
351 查看
题目
合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。样例
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null
解题
两两合并合并ab得到c
合并cd得到e
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param lists: a list of ListNode * @return: The head of one sorted list. */ public ListNode mergeKLists(List<ListNode> lists) { // write your code here if(lists == null || lists.size()==0) return null; ListNode head = lists.get(0); for(int i=1;i<lists.size();i++){ ListNode list = lists.get(i); if(list!=null) head = merge(head,list); } // print(head); return head; } public void print(ListNode head){ while(head!=null){ System.out.print(head.val + "->"); head = head.next; } System.out.println(); } public ListNode merge(ListNode l1,ListNode l2){ if(l1==null) return l2; if(l2==null) return l1; ListNode head = new ListNode(-1); ListNode cur = head; while(l1!=null && l2!=null){ if(l1.val <=l2.val){ cur.next = l1; l1 = l1.next; }else{ cur.next = l2; l2 = l2.next; } cur = cur.next; } if(l1!=null) cur.next = l1; if(l2!=null) cur.next = l2; return head.next; } }
利用优先队列
public ListNode mergeKLists(List<ListNode> lists) { // write your code here if(lists == null || lists.size()==0) return null; ListNode head = new ListNode(0); PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){ public int compare(ListNode a ,ListNode b){ if(a.val > b.val) return 1; else if(a.val == b.val) return 0; return -1; } }); for(ListNode list:lists){ if(list!=null) q.add(list); } ListNode p = head; while(q.size() >0){ ListNode tmp = q.poll(); p.next = tmp; if(tmp.next!=null){ q.add(tmp.next); } p = p.next; } return head.next; }
相关文章推荐
- MongoDB数据库基本用法
- 4JQuery与Dom操作
- Java 子窗口
- 【转】listview点击不变色的设置
- 项目中出现的词的解释
- 3JQuery与Css
- python 打印json格式的数据中文显示问题
- 设计模式——命令模式
- 最长递增子序列
- openssl升级,解决Padding Oracle漏洞
- Python使用cookielib模块操作cookie的实例教程
- Centos Linux 开启端口 - 解决Centos发布服务外网访问不了的问题
- Linux下安装libiconv使php支持iconv函数
- SharePoint 2013 基于数据库的表单认证FBA,并添加注册界面
- Java 并发专题 : Timer的缺陷 用ScheduledExecutorService替代
- Unity 玩家设置
- mysqldump参数详细说明
- 命令行 java文本编辑工具 重载 内存区域 栈 堆
- WebView使用详解(二)——WebViewClient与常用事件监听
- 由一个简单示例 引出java继承中父子类成员变量共享问题 以及super的使用