[路飞]_每天刷leetcode_43(合并K个升序链表Merge K Sorted Lists)

138 阅读1分钟

合并K个升序链表(Merge K Sorted Lists)

LeetCode传送门23. 合并K个升序链表

原题

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

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:

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

Input: lists = []
Output: []



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

Constraints:

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • lists[i] is sorted in ascending order.
  • The sum of lists[i].length won't exceed 10^4.

思考线


解题思路

这道题我看到后最直观的感觉思路是

  1. 设置一个空链表来保存最后的结果
  2. 每个链表的第一个元素站出来,比较其中最小的放入最终要合并的空链表内,并把对应的链表向后挪动一位。
  3. 重复2步骤的操作,直到所有的链表都指向null

根据以上思路我们完成了以下代码


/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
    if (!lists.length) return null;
    const resList = new ListNode();
    let temp = resList;
    outer:
    while (lists.find(item => item)) {
        let min = 0;
        for (let i = 0; i < lists.length; i++) {
            if (!lists[i]) {
                lists.splice(i, 1);
                continue outer;
            }
            if (lists[i].val < lists[min].val) {
                min = i;
            }
        }

        temp.next = lists[min];
        lists[min] = lists[min].next;
        temp = temp.next;
        // temp.next = null
        if (!lists[min]) lists.splice(min, 1);
    }

    return resList.next;
};

分析这个解法的时间复杂度

我们假设数组中一共有k个链表,每次找到最小值的时间复杂度为 k, 假设最长的链表为n,那么我们要合入kn个元素,所以最终的时间复杂度为k^2n