package com.heu.wsq.niuke.top200;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* 合并k个已排序的链表
* @author wsq
* @date 2021/6/2
* 描述
* 合并k个已排序的链表并将其作为一个已排序的链表返回。分析并描述其复杂度。
* 示例1
* 输入:
* [{1,2,3},{4,5,6,7}]
* 返回值:
* {1,2,3,4,5,6,7}
*/
public class MergeKLists {
/**
* 既然是多个列表合并,我们能不能折半合并,采用分治的思想降低计算的复杂性
* @param lists
* @return
*/
public ListNode mergeKLists1(ArrayList<ListNode> lists) {
if(lists == null || lists.size() == 0){
return null;
}
int n = lists.size();
ListNode root = mergeLists(lists, 0, n-1);
return root;
}
private ListNode mergeLists(ArrayList<ListNode> lists, int left, int right) {
if(left == right){
return lists.get(left);
}
int mid = (left + right) >> 1;
ListNode listNode = mergeLists(lists, left, mid);
ListNode rightNode = mergeLists(lists, mid + 1, right);
ListNode root = merge(listNode, rightNode);
return root;
}
private ListNode merge(ListNode listNode, ListNode rightNode) {
ListNode hair = new ListNode(-1);
ListNode h = hair, p = listNode, q = rightNode;
while (p != null || q != null){
if(p == null){
h.next = q;
q = q.next;
}else if(q == null){
h.next = p;
p = p.next;
}else{
if(p.val < q.val){
h.next = p;
p = p.next;
}else{
h.next = q;
q = q.next;
}
}
h = h.next;
}
return hair.next;
}
/**
* 优先队列解法
* @param lists
* @return
*/
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists == null || lists.size() == 0){
return null;
}
int n = lists.size();
ListNode[] pArr = new ListNode[n];
int i = 0;
PriorityQueue<PQNode> pq = new PriorityQueue<>(new Comparator<PQNode>(){
public int compare(PQNode o1, PQNode o2){
return o1.val - o2.val;
}
});
for(ListNode node: lists){
pArr[i] = node;
if(node != null){
pq.offer(new PQNode(node.val, i));
}
i++;
}
ListNode hair = new ListNode(-1);
ListNode p = hair;
while(!pq.isEmpty()){
PQNode pqNode = pq.poll();
ListNode node = new ListNode(pqNode.val);
p.next = node;
int pos = pqNode.pos;
pArr[pos] = pArr[pos].next;
if(pArr[pos] != null){
pq.offer(new PQNode(pArr[pos].val, pos));
}
p = p.next;
}
return hair.next;
}
static class PQNode{
Integer val;
Integer pos;
public PQNode(int val, Integer pos){
this.val = val;
this.pos = pos;
}
}
}
合并k个已排序的链表(分治、优先队列)
最新推荐文章于 2025-03-03 09:55:03 发布