头图

Niuke.com High-Frequency Algorithm Question Series-BM5-Merge k sorted linked lists

Topic description

Merge k ascending linked lists and return the result as an ascending linked list with its head node.

See the original title: BM5 merge k sorted linked lists

Solution 1: Divide and Conquer

Divide and conquer, you can decompose a big problem into small problems, and then continue to decompose into the smallest sub-problems and solve them.

The specific processing process is as follows. The k linked lists are decomposed into two parts for processing, the two parts are processed recursively, and the method in BM4 to merge two sorted linked lists is called to merge the two merged linked lists. The condition of the smallest sub-problem is :

  • If there is no linked list to be merged, return empty directly.
  • If there is only one linked list, there is no need to merge, and the linked list is returned directly.

If it is not satisfied, it needs to continue to decompose and process recursively.

Note: BM4 merges two sorted linked lists, please refer to Niuke.com High Frequency Algorithm Questions Series - BM4 - Merge Two Sorted Linked Lists.

code

 import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;

public class Bm005 {
    /**
     * 分治法
     *
     * @param lists
     * @return
     */
    public static ListNode mergeKLists(List<ListNode> lists) {
        // 如果没有待合并的链表,直接返回空
        if (lists == null || lists.size() == 0) {
            return null;
        }
        // 如果只有一个链表,则不需要合并,直接返回该链表
        if (lists.size() == 1) {
            return lists.get(0);
        }
        int left = 0, right = lists.size();
        int mid = (left + right) / 2;
        // 递归调用当前方法将原有的链表集合分成2部分分别进行合并
        // 然后调用 BM4 合并两个排序的链表 中的方法将2个合并好的链表进行合并
        return Bm004.merge(mergeKLists(lists.subList(0, mid)), mergeKLists(lists.subList(mid, right)));
    }

    public static void main(String[] args) {
        ListNode listNode1 = ListNode.testCase3();
        System.out.println("链表一");
        ListNode.print(listNode1);
        ListNode listNode2 = ListNode.testCase4();
        System.out.println("链表二");
        ListNode.print(listNode2);
        ListNode listNode3 = new ListNode(7);
        System.out.println("链表三");
        ListNode.print(listNode3);
        ArrayList<ListNode> lists = Lists.newArrayList(listNode1, listNode2, listNode3);
        ListNode result = mergeKLists(lists);
        // 测试用例,期望输出: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
        System.out.println("合并后的链表");
        ListNode.print(result);
    }
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!