(Java)LeetCode-23. Merge k Sorted Lists

86人阅读 评论(0)

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

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0){
return null;
}
ListNode res = merge(lists,0,lists.length-1);
return res;
}

private ListNode merge(ListNode[] lists, int left, int right) {
// TODO Auto-generated method stub
if(right <= left){
return lists[right];
}

int mid = left + (right - left)/2;
ListNode Listleft = merge(lists,left,mid);
ListNode Listright= merge(lists,mid+1,right);

ListNode res = mergetwo(Listleft,Listright);

return res;
}

private ListNode mergetwo(ListNode listleft, ListNode listright) {
// TODO Auto-generated method stub
while(listleft != null || listright != null){
if(listleft == null){
return temp.next;
}else if(listright == null){
return temp.next;
}else if(listleft.val >= listright.val){
listright = listright.next;
}else{
listleft = listleft.next;
}
}
return temp.next;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：14918次
• 积分：1055
• 等级：
• 排名：千里之外
• 原创：96篇
• 转载：0篇
• 译文：0篇
• 评论：2条
文章分类
阅读排行
评论排行
最新评论