Merge k Sorted Lists
2015-06-15 17:03
253 查看
leetcode
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.使用一个大小为K的堆来维持找当前的最小元素。
一、Java当中的PriorityQueue如何使用?
class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
对于上面的节点,需要重新实现Comparator接口
实现方式为:
class MyCompare implements Comparator{ public int compare(Object o1, Object o2){ ListNode n1 = (ListNode)o1; ListNode n2 = (ListNode)o2; if(n1.val < v2.val){ return -1; }else if(n1.val==n2.val){ return 0; }else{ return 1; } } }
注意上面的定义方式,对于升序排列,则当小于时返回-1,大于时返回1,else 返回 0.
另外也可以也可以使用匿名函数的方式。
Comparator<ListNode> mc = new Comparator<ListNode>(){ public int compare(ListNode n1, ListNode n2){ //should pay attention to the return value below if(n1.val < n2.val){ return -1; }else if(n1.val==n2.val){ return 0; }else{ return 1; } } };
算法总体的代码实现为:
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null||lists.length==0) return null;
Comparator<ListNode> mc = new Comparator<ListNode>(){ public int compare(ListNode n1, ListNode n2){ //should pay attention to the return value below if(n1.val < n2.val){ return -1; }else if(n1.val==n2.val){ return 0; }else{ return 1; } } };
//这里需要注意,在新的java版本当中,不能指定泛型的类型,也就是下面的代码如果定义为Queue<ListNode> queue = new PriorityQueue<ListNode>(lists.length,mc);会报错
//实际当中,应该是把其当做Object来看待的,在实际使用时,可以对其进行强制类型转化,即可
Queue queue = new PriorityQueue(lists.length,mc);
for(int i=0;i<lists.length;i++){
//there may be the contents in the lists is null, this is a corner case
if(lists[i]!=null)
queue.add(lists[i]);
}
ListNode head=null;
ListNode prenode=null;
while(!queue.isEmpty()){
ListNode top = (ListNode)queue.poll();
ListNode next = top.next;
top.next=null;
if(head==null){
head=top;
prenode=top;
}else{
prenode.next=top;
prenode=top;
}
if(next!=null){
queue.add(next);
}
}
return head;
}
}
相关文章推荐
- Solr相似度算法四:IBSimilarity
- 黑马程序员——java基础之语法(二)
- Spring 系列: Spring 框架简介
- 玩玩PCtoLCD,得到指定大小字模库
- 用Fildder抓取Android的HTTP包
- 第12章-图形用户接口
- root权限引发的/sbin/init不存在故障的血案 推荐
- [转]KAGGLE ENSEMBLING GUIDE
- fcitx日语输入法添加
- java.sql.SQLException: Connection is closed
- 利用移位、加减法实现整数开平方算法的方法(转)
- 安全 加密解密 在线工具
- js/jQuery判断浏览器名称、内核版本、浏览器壳
- java 记录一下socket的server与clien
- 面试题 IQ
- 【Feasibility of Learning】林轩田机器学习基石
- 【BZOJ】【2694】Lcm
- [转] boost::any的用法、优点和缺点以及源代码分析
- Solr相似度算法三:DRFSimilarity框架介绍
- oracle数据库cpu使用率高