您的位置:首页 > 其它

LeetCode 023 Merge k Sorted Lists

2015-03-19 14:21 363 查看
题目

把k个排序号的链表连接成一个有序链表。

代码

public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
if(lists == null){
return null;
}

PriorityQueue<ListNode> record =
new PriorityQueue<ListNode>(
new Comparator<ListNode>() {

@Override
public int compare(ListNode o1, ListNode o2) {

return o1.val-o2.val;
}
});

for(Iterator<ListNode> i =lists.iterator();i.hasNext();){
ListNode cur = i.next();
while(cur !=null){
record.add(cur);
cur = cur.next;
}
}

ListNode dummy = new ListNode(Integer.MAX_VALUE);
ListNode curNode = dummy;

while(!record.isEmpty()){
curNode.next=new ListNode(record.poll().val);
curNode = curNode.next;
}
return dummy.next;

}
}

思考

1 时间:Nlog(k) N 是总数 log(k)是每次插入堆或者取出堆的需要操作的次数

2 可以换divide and conquar来做,时间一样
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: