Leetcode - Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

[分析] 有了Merge 2 sorted lists的铺垫做这题就容易了,自己写了递归版的method1, 翻看历史记录,有迭代版的和heap sort版本,觉得method1 & 2写得更顺手些。感觉迭代方式挺巧妙的,哈哈


public class Solution {
// Method 1: 递归
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0)
return null;
return divide(lists, 0, lists.length - 1);
}
private ListNode divide(ListNode[] lists, int beg, int end) {
if (beg != end) {
int mid = beg + (end - beg) / 2;
return merge2Lists(divide(lists, beg, mid), divide(lists, mid + 1, end));
} else {
return lists[beg];
}
}
// Method 2: 迭代
public ListNode mergeKLists2(ArrayList<ListNode> lists) {
int last = lists.size() - 1;
if(last < 0)
return null;

while(last > 0){
int curr = 0;
while(curr < last)
lists.set(curr, merge2Lists(lists.get(curr++), lists.get(last--)));
}
return lists.get(0);
}
private ListNode merge2Lists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode head = new ListNode(0);
ListNode m = head;
ListNode p = l1, q = l2;
while (p != null && q != null) {
if (p.val < q.val) {
m.next = p;
p = p.next;
} else {
m.next = q;
q = q.next;
}
m = m.next;
}
if (p != null)
m.next = p;
if (q != null)
m.next = q;
return head.next;
}
// Method 3: heap sort(O(nlogk)), n nodes, k lists
public ListNode mergeKLists(ArrayList<ListNode> lists) {

if(lists == null || lists.size() == 0)
return null;

Comparator<ListNode> comparator = new Comparator<ListNode>(){
public int compare(ListNode l1, ListNode l2){
if(l1.val < l2.val)
return -1;
else if(l1.val > l2.val)
return 1;
else
return 0;
}
};

//initial
PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(lists.size(), comparator);
for(ListNode node:lists){
if(node != null)
heap.offer(node);
}

ListNode head = null, curr = head;
while(!heap.isEmpty()){
if(head == null){
head = heap.poll();//delete min from heap
curr = head;
}else{
curr.next = heap.poll();
curr = curr.next;
}
if(curr.next != null)
heap.offer(curr.next);
}

return head;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值