您的位置:首页 > 其它

【leetcode】23. Merge k Sorted Lists

2016-07-05 00:34 246 查看

题目描述:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

解题分析:

解题思路很简单,就是先两两排序,不断减小链表数量,最后将所有数组织成一个有序链表

具体代码:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public static ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0)
return null;
if(lists.length==1)
return lists[0];
int from=0;
int to=lists.length-1;
//两两排序时使用类似二分查找的方法缩小时间复杂度
while(from!=to){
//from+to等于偶数
if(((from+to)&1)==0){
int mid=(from+to)>>1;
for(int i=0;i<mid;i++){
lists[i]=mergeTwoLists(lists[i], lists[mid+1+i]);
}
to=mid;
}
else{
int mid=(from+to)>>1;
for(int i=0;i<=mid;i++){
lists[i]=mergeTwoLists(lists[i], lists[mid+1+i]);
}
to=mid;
}
}
return lists[0];
}
//和并两个链表的方法
public static ListNode mergeTwoLists(ListNode head1, ListNode head2) {
if(head1==null)
return head2;
if(head2==null)
return head1;
ListNode head=null;
ListNode current=null;
if(head1.val<=head2.val){
head=head1;
head1=head1.next;
head.next=null;
}
else{
head=head2;
head2=head2.next;
head.next=null;
}
current=head;
while(head1!=null&&head2!=null){
if(head1.val<=head2.val){
current.next=head1;
current=current.next;
head1=head1.next;
current.next=null;
}
else{
current.next=head2;
current=current.next;
head2=head2.next;
current.next=null;
}
}
if(head1!=null){
current.next=head1;
}
if(head2!=null){
current.next=head2;
}
return head;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: