您的位置:首页 > 其它

leetcode 23. Merge k Sorted Lists

2016-06-11 23:11 375 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

合并k个有序的链表成一个有序的链表.

用java中优先队列做,java中的优先队列是基于优先级堆的

public class A23MergekSortedLists {
// 130 test cases passed.
// Runtime: 12 ms
public ListNode mergeKLists(ListNode[] lists) {
// 优先队列
PriorityQueue<ListNode> priorityQueue = new PriorityQueue<ListNode>(new Comparator<ListNode>() {
public int compare(ListNode n1, ListNode n2) {
// 升序
return n1.val - n2.val;
}
});
// 把每个链表的头结点加入优先队列
for(int i = 0; i < lists.length; i++) {
if(lists[i] != null) {
priorityQueue.add(lists[i]);
}
}

ListNode node = new ListNode(0);
ListNode ans = node;
// 把优先队列中优先级最高的出队,如果它的下一个节点不为空,则把下一个节点加入优先队列中,直到队列为空
while(!priorityQueue.isEmpty()) {
node.next = priorityQueue.poll();
if(node.next.next != null) {
priorityQueue.add(node.next.next);
}
node = node.next;
}
return ans.next;
}
}
后来看到有用分而治之的方法,转换成2个链表的合并.

// 130 test cases passed.
// Runtime: 5 ms
public ListNode mergeKLists(ListNode[] lists) {
return partition(lists, 0, lists.length - 1);
}

public ListNode partition(ListNode[] lists, int start, int end) {
if(start == end) {
return lists[start];
}

if(start < end) {
int mid = (start + end) / 2;
ListNode l1 = partition(lists, start, mid);
ListNode l2 = partition(lists, mid + 1, end);
return mergeTwoLists(l1, l2);
}
return null;
}

// 21. Merge Two Sorted Lists
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l2 == null) return l1;
if(l1 == null) return l2;

if(l1.val > l2.val) {
ListNode temp = l2;
temp.next = mergeTwoLists(l1, l2.next);
return temp;
} else {
ListNode temp = l1;
temp.next = mergeTwoLists(l1.next, l2);
return temp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode