题目:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
我的答案:
解法一:暴力法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
//ListNode node = new ListNode(0);
if(lists==null||lists.length==0){
return null;
}
//node.next = lists.get(0);
ListNode temp = lists[0];
for(int i=1;i<lists.length;i++){
temp = mergeTwoLists(temp,lists[i]);
}
return temp;
}
public ListNode mergeTwoLists(ListNode l1,ListNode l2){
ListNode node = new ListNode(0);
ListNode temp = node;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
temp.next = l1;
l1 = l1.next;
}else{
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
if(l1!=null){
temp.next = l1;
}
if(l2!=null){
temp.next = l2;
}
return node.next;
}
}
解法二:分治法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null||lists.length==0){
return null;
}
return merge(lists,0,lists.length-1);
}
public ListNode merge(ListNode[] lists,int left,int right){
if(left == right){
return lists[left];
}
int mid = (left+right)/2;
ListNode l1 = merge(lists,left,mid);
ListNode l2 = merge(lists,mid+1,right);
return mergeTwoLists(l1,l2);
}
public ListNode mergeTwoLists(ListNode l1,ListNode l2){
ListNode node = new ListNode(0);
ListNode temp = node;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
temp.next = l1;
l1 = l1.next;
}else{
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
if(l1!=null){
temp.next = l1;
}
if(l2!=null){
temp.next = l2;
}
return node.next;
}
}
官方题解:
官方题解好几种方法
作者:LeetCode
链接:链接
来源:力扣(LeetCode)
总结:
还是要熟悉算法:分治法
来源:CSDN
作者:wyplj_sir
链接:https://blog.csdn.net/wyplj2015/article/details/103482983