题意:
给你k个有序的链表,让你合并成一个有序的链表。
思路:
直接一个一个合并的话,耗时448ms,超时了,对于这种方法,最先合并的数据可能会多次和后面的数据进行比较,这大大浪费了时间,运行时间会大于n^3。运用分治的方法,如果分成两组两组比较,合并好的数据之间就不会在进行比较,大大减少了比较的次数,运行时间最高为logn*n^2。
//java是完全的面向对象编程,不能在类外定义函数,调用函数必须先生成对象,,这点和c++很不同。。。
java代码:
class Solution {
public ListNode dfs(ListNode[] lists,int s,int e){
if(s==e){
return lists[s];
}
ListNode root = new ListNode(0);
ListNode temp = root;
int mid = (s+e)>>1;
ListNode head = dfs(lists,s,mid);
ListNode list = dfs(lists,mid+1,e);
while(head!=null||list!=null){
if(head==null){
temp.next = list;
list = list.next;
}
else if(list==null||head.val<=list.val){
temp.next = head;
head = head.next;
}
else{
temp.next = list;
list = list.next;
}
temp = temp.next;
}
return root.next;
}
public ListNode mergeKLists(ListNode[] lists) {
int len = lists.length;
if(len==0)
return null;
int s = 0;
int e = len-1;
Solution ss = new Solution();
return ss.dfs(lists,s,e);
}
Solution(){}
}