23. Merge k Sorted Lists

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

 

Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

Example 2:

Input: lists = []
Output: []

Example 3:

Input: lists = [[]]
Output: []

 

// 常规做法是正常的两两合并,最终将多个合并成一个。即是先将前两个合并,然后再与第三个合并,再与第四个,第五个。。。直到所有合并结束

// 使用这种二分思想,可以减少遍历的节点数量

public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0) return null;
// 从外向内合并首尾两个链表
int rightIndex = lists.length-1;
while(rightIndex > 0){
int low = 0, high = rightIndex;
while(low < high){
lists[low]= merge(lists[low], lists[high]); // 详见合并两个排序列表,https://www.cnblogs.com/MarkLeeBYR/p/16853659.html
low++;
high--;
}
rightIndex=high;
}
return lists[0];
}

例如有8个链表,初始rightIndex=7,

假如有8个链表,初始rightIndex=7

low=0,high=7:
  merge(lists[0], lists[7])
    merge(lists[1], lists[6])
  merge(lists[2], lists[5])
  merge(lists[3], lists[4])
  rightIndex=3
low=0,high=3:
  merge(lists[0], lists[3])
  merge(lists[1], lists[2])
  rightIndex=1
low=0,high=1:
  merge(lists[0], lists[1])
  rightIndex=0

 

 

posted @   MarkLeeBYR  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示