leetcode 困难 —— 合并K个升序链表(超详细思路)

题目:
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。

题解:
这道题真的是简单
看一眼数据范围

首先 lists[i].length 的总和不超过 10^4,这说明,我们可以把每个 list 中的所有元素放进优先队列里,然后依次取出,但是呢,这个是 nlogn,还是慢了

再看一眼,-10^4 <= lists[i][j] <= 10^4,直接 ddd[20000],然后就不需要排序了,ddd[i] 的值,等于所有 list 中等于 i 值的元素个数,这样把所有 list 遍历一遍,给 ddd 数组赋值,最后再遍历一遍 ddd 数组,创建保存结果的链表,没了

代码如下:

class Solution {
public:
    int ddd[20005];
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        for(int i = 0; i < lists.size(); i++) {
            ListNode* temp = lists[i];
            while(temp != NULL) {
                ddd[(temp -> val) + 10000]++;
                temp = temp -> next;
            }
        }
        ListNode* res = new ListNode();
        ListNode* temp = res;
        for(int i = 0; i <= 20000; i++) {
            while(ddd[i] != 0) {
                temp -> next = new ListNode(i - 10000);
                temp = temp -> next;
                ddd[i]--;
            }
        }
        return res -> next;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_52212261/article/details/128897905