目录
题目链接
题目
解题思路
利用分治的思想,将一分成二,二分成四,最后划分成两两结合即可
代码
java
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode Merge(ListNode pHead1,ListNode pHead2){
if(pHead1==null){
return pHead2;
}
if(pHead2==null){
return pHead1;
}
ListNode dummyNode =new ListNode(0);
ListNode cur=dummyNode;
while(pHead1!=null&&pHead2!=null){
if(pHead2.val<pHead1.val){
cur.next=pHead2;
pHead2=pHead2.next;
}else{
cur.next=pHead1;
pHead1=pHead1.next;
}
cur=cur.next;
}
while(pHead1!=null){
cur.next=pHead1;
pHead1=pHead1.next;
cur=cur.next;
}
while(pHead2!=null){
cur.next=pHead2;
pHead2=pHead2.next;
cur=cur.next;
}
return dummyNode.next;
}
public ListNode divide(ArrayList<ListNode> lists,int left,int right){
if(left>right){
return null;
}
if(left==right){
return lists.get(left);
}
int mid=(left+right)/2;
return Merge(divide(lists,left,mid),divide(lists,mid+1,right));
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类ArrayList
* @return ListNode类
*/
public ListNode mergeKLists (ArrayList<ListNode> lists) {
// write code here
return divide(lists,0,lists.size()-1);
}
}