xcghvgshjdfghsd

# 1 题目

LeetCode第23题,合并k个有序的链表.

# 2 暴力法

``````List<Integer> s = new ArrayList<>();
for(ListNode x:lists)
{
while(x != null)
{
x = x.next;
}
}
s.sort((a,b) -> {return a.compareTo(b);});
ListNode result = new ListNode(0);
ListNode t = result;
for(Integer x:s)
{
t.next = new ListNode(x);
t = t.next;
}
return result.next;``````

``s.sort((a,b)->{return a>b ? 1 : -1;});``

``s.sort((a,b)->{return a.compareTo(b);});``

# 3 直接合并法

``````ListNode result = new ListNode(0);
ListNode t = result;
int len = lists.length;
int nullNodeNums = 0;
for(boolean [] b = new boolean[len];nullNodeNums<len;)
{
int min = Integer.MAX_VALUE;
int minIndex = -1;
for(int index = 0;index<len;++index)
{
ListNode x = lists[index];
if(x == null)
{
if(!b[index])
{
b[index] = true;
++nullNodeNums;
}
}
else if(x.val < min)
{
min = x.val;
minIndex = index;
}
}
if(minIndex != -1)
{
t.next = new ListNode(min);
t = t.next;
lists[minIndex] = lists[minIndex].next;
}
}
return result.next;``````

# 4 优先队列

``````PriorityQueue<Integer> queue = new PriorityQueue<>();
for(ListNode x:lists)
{
while(x != null)
{
x = x.next;
}
}
ListNode s = new ListNode(0);
ListNode t = s;
while(!queue.isEmpty())
{
t.next = new ListNode(queue.poll());
t = t.next;
}
return s.next;``````

# 5 两两合并法

``````public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0)
return null;
ListNode t = lists[0];
for(int i=1;i<lists.length;++i)
t = merge(t, lists[i]);
return t;
}
//public ListNode merge(ListNode a,ListNode b)``````

merge为直接合并两个链表的操作,不难,就不贴代码了,首先赋值t为第一个链表,然后依次合并t与剩下的n-1个链表.

# 6 分治法

``````public ListNode f(int start,int end)
{
int len = end - start;
if(len <= 1)
return lists[start];
ListNode l = f(start,start+len/2);
ListNode r = f(start+len/2,end);
return merge(l, r);
}``````

github

302 声望
632 粉丝
0 条评论