`
SunnyYoona
  • 浏览: 366929 次
社区版块
存档分类
最新评论

[LeetCode]23.Merge k Sorted Lists

 
阅读更多

【题目】

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

【分析】

【代码】

/*********************************
*   日期:2015-01-06
*   作者:SJF0115
*   题目: 23.Merge k Sorted Lists
*   来源:https://oj.leetcode.com/problems/merge-k-sorted-lists/
*   结果:Time Limit Exceeded
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
#include <vector>
using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x),next(NULL){}
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        ListNode *head = NULL;
        if(lists.size() == 0){
            return head;
        }//if
        for(int i = 0;i < lists.size();i++){
            head = mergeTwoLists(head,lists[i]);
        }//for
        return head;
    }
private:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(l1 == NULL) return l2;
        if(l2 == NULL) return l1;

        if(l1->val < l2->val) {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        } else {
            l2->next = mergeTwoLists(l2->next, l1);
            return l2;
        }
    }
};
// 创建链表
ListNode* CreateList(int A[],int n){
    ListNode *head = NULL;
    if(n <= 0){
        return head;
    }//if
    head = new ListNode(A[0]);
    ListNode *p1 = head;
    for(int i = 1;i < n;i++){
        ListNode *node = new ListNode(A[i]);
        p1->next = node;
        p1 = node;
    }//for
    return head;
}

int main() {
    Solution solution;
    vector<ListNode*> vecs;
    int A[] = {1,2,4,7,9};
    int B[] = {3,5,8,10,11,12};
    int C[] = {6,10,13};
    int D[] = {15,16,17,23};

    ListNode* head1 = CreateList(A,5);
    ListNode* head2 = CreateList(B,6);
    ListNode* head3 = CreateList(C,3);
    ListNode* head4 = CreateList(D,4);

    vecs.push_back(head1);
    vecs.push_back(head2);
    vecs.push_back(head3);
    vecs.push_back(head4);

    ListNode *head = solution.mergeKLists(vecs);
    // 输出
    ListNode *p = head;
    while(p){
        cout<<p->val<<" ";
        p = p->next;
    }//while
    cout<<endl;
}

这种方法超时。。。。。。。

【分析二】

采用最小优先级队列。

第一步:把非空的链表装进最小优先级队列中。

第二步:遍历最小优先级队列,直到最小优先级队列空为止。每次遍历,都能从最小优先级队列中取出具有当前最小的元素的链表。

如果除最小元素之外,链表不空,重新装进最小优先级队列中。

【代码二】

/*********************************
*   日期:2015-01-06
*   作者:SJF0115
*   题目: 23.Merge k Sorted Lists
*   来源:https://oj.leetcode.com/problems/merge-k-sorted-lists/
*   结果:AC
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
#include <queue>
using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x),next(NULL){}
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        ListNode *head = new ListNode(-1);
        ListNode *p = head;
        // 最小优先级队列
        priority_queue<ListNode*,vector<ListNode*>,cmp> Heap;
        // 链表加入优先级队列
        for(int i = 0;i < lists.size();i++){
            if(lists[i] != NULL){
                Heap.push(lists[i]);
            }//if
        }//for
        // merge
        while(!Heap.empty()){
            // 最小的
            ListNode *list = Heap.top();
            Heap.pop();
            p->next = list;
            p = list;
            if(list->next != NULL){
                Heap.push(list->next);
            }//if
        }//while
        return head->next;
    }
private:
    // 用于最小优先级队列
    struct cmp {
        bool operator()(ListNode* node1, ListNode* node2) {
            return node1->val > node2->val;
        }//bool
    };
};
// 创建链表
ListNode* CreateList(int A[],int n){
    ListNode *head = NULL;
    if(n <= 0){
        return head;
    }//if
    head = new ListNode(A[0]);
    ListNode *p1 = head;
    for(int i = 1;i < n;i++){
        ListNode *node = new ListNode(A[i]);
        p1->next = node;
        p1 = node;
    }//for
    return head;
}

int main() {
    Solution solution;
    vector<ListNode*> vecs;
    int A[] = {1,2,4,7,9};
    int B[] = {3,5,8,10,11,12};
    int C[] = {6,10,13};
    int D[] = {15,16,17,23};

    ListNode* head1 = CreateList(A,5);
    ListNode* head2 = CreateList(B,6);
    ListNode* head3 = CreateList(C,3);
    ListNode* head4 = CreateList(D,4);

    vecs.push_back(head1);
    vecs.push_back(head2);
    vecs.push_back(head3);
    vecs.push_back(head4);

    ListNode *head = solution.mergeKLists(vecs);
    // 输出
    ListNode *p = head;
    while(p){
        cout<<p->val<<" ";
        p = p->next;
    }//while
    cout<<endl;
}



【分析三】

I think my code's complexity is alsoO(nlogk)and not using heap or priority queue, n means the total elements and k means the size of list.

The mergeTwoLists functiony in my code comes from the problemMerge Two Sorted Listswhose complexity obviously isO(n), n is the sum of length of l1 and l2.

To put it simpler, assume the k is 2^x, So the progress of combination is like a full binary tree, from bottom to top. So on every level of tree, the combination complexity is n, beacause every level have all n numbers without repetition. The level of tree is x, ie logk. So the complexity isO(nlogk).

for example, 8 ListNode, and the length of every ListNode is x1, x2, x3, x4, x5, x6, x7, x8, total is n.

on level 3: x1+x2, x3+x4, x5+x6, x7+x8 sum: n

on level 2: x1+x2+x3+x4, x5+x6+x7+x8 sum: n

on level 1: x1+x2+x3+x4+x5+x6+x7+x8 sum: n

total 3n, nlog8


【代码三】

/*********************************
*   日期:2015-01-07
*   作者:SJF0115
*   题目: 23.Merge k Sorted Lists
*   来源:https://oj.leetcode.com/problems/merge-k-sorted-lists/
*   结果:AC
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
#include <limits.h>
#include <queue>
using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x),next(NULL){}
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        int count = lists.size();
        if(count == 0){
            return NULL;
        }//if
        if(count == 1){
            return lists[0];
        }//if
        // 链表集合分成两份
        vector<ListNode *> leftLists;
        for(int i = 0;i < count/2;i++){
            leftLists.push_back(lists.back());
            lists.pop_back();
        }//for
        // 分治
        return mergeTwoLists(mergeKLists(leftLists),mergeKLists(lists));
    }
private:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode *head = new ListNode(-1);
        for(ListNode *p = head;l1 != NULL || l2 != NULL;p = p->next){
            int val1 = (l1 == NULL) ? INT_MAX : l1->val;
            int val2 = (l2 == NULL) ? INT_MAX : l2->val;
            if(val1 <= val2){
                p->next = l1;
                l1 = l1->next;
            }//if
            else{
                p->next = l2;
                l2 = l2->next;
            }//else
        }//for
        return head->next;
    }
};
// 创建链表
ListNode* CreateList(int A[],int n){
    ListNode *head = NULL;
    if(n <= 0){
        return head;
    }//if
    head = new ListNode(A[0]);
    ListNode *p1 = head;
    for(int i = 1;i < n;i++){
        ListNode *node = new ListNode(A[i]);
        p1->next = node;
        p1 = node;
    }//for
    return head;
}

int main() {
    Solution solution;
    vector<ListNode*> vecs;
    int A[] = {1,2,4,7,9};
    int B[] = {3,5,8,10,11,12};
    int C[] = {6,10,13};
    int D[] = {15,16,17,23};

    ListNode* head1 = CreateList(A,5);
    ListNode* head2 = CreateList(B,6);
    ListNode* head3 = CreateList(C,3);
    ListNode* head4 = CreateList(D,4);

    vecs.push_back(head1);
    vecs.push_back(head2);
    vecs.push_back(head3);
    vecs.push_back(head4);

    ListNode *head = solution.mergeKLists(vecs);
    // 输出
    ListNode *p = head;
    while(p){
        cout<<p->val<<" ";
        p = p->next;
    }//while
    cout<<endl;
}


分享到:
评论

相关推荐

    程序员面试宝典LeetCode刷题手册

    第四章 Leetcode 题解 1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters ...23. Merge k Sorted Lists 24. Swap Nodes in Pairs 25. Reverse Nodes in k-Group 26. Remove Dupli

    LeetCode Merge 2 Sorted Lists解决方案

    LeetCode Merge 2 Sorted Lists解决方案

    leetcode中文版-LeetCode:力码

    23.Merge k Sorted Lists(solve1) LeetCode 23.Merge k Sorted Lists(solve2) LeetCode 86.Partition List LeetCode 92.Reverse Linked List II LeetCode 138.Copy List with Random Pointer LeetCode 142.Linked ...

    LeetCode 23. 合并K个排序链表

    链接:https://leetcode-cn.com/problems/merge-k-sorted-lists 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 思路 很简单,因为是小的先插入,使用优先队列实现。把k个链表当前第一个...

    lrucacheleetcode-leetcode:leetcode

    lru缓存leetcode leetcode 1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 7. Reverse Integer 9. ...

    lrucacheleetcode-leetcode-journal:记录所有LeetCode挑战的存储库

    lru缓存leetcode 力扣日记 欢迎来到我的 LeetCode 期刊库。 我的每个问题都将包括一个初始计划阶段,在这个阶段我将用我自己的话来定义问题,我将如何解决这个问题,并且所有内容都将首先用伪代码写出来。 当我解决...

    LeetCode最全代码

    26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates...

    MergeTwoSortedLinkedList.java

    【Leetcode】Merge Two Sorted Lists

    leetcode跳跃-leetcode:leetcode一天一次

    leetcode 跳跃 leetcode 动态规划,背包问题 01背包问题:416. Partition Equal Subset Sum 最长回文:5. Longest Palindromic Substring - 字数组余数:523. Continuous Subarray Sum - 无重复字符的最长子串:3. ...

    leetcode答案-LeetCode-Trip:LeetCode刷题代码,大佬勿入

    leetcode 答案 LeetCode-Trip LeetCode刷题代码,大佬勿入。 为一年后的研究生找工作准备 目标是BAT的算法岗哈哈哈哈哈 争取做到每日一更 嗯…… 19.10.22:鸽了这么久,我又回来了……主要在实验室天天没啥事,过于...

    leetcode分类-leetcode:leetcode问题的代码

    leetcode 分类leetcode 问题分类 leetcode代码仓库,我的解题思路写在我的博客里: leetcode 代码库,我博客上的解题思路: mkdir 列表: 大批 #1:Two Sum #4:Median ...Sorted ...#23:Merge k Sorted Lists

    leetcode添加元素使和等于-programmer_practices:算法实践

    leetcode添加元素使和等于 programmer_practices algorithm practices 最优解Book: 双栈实现getMin Stack. 双栈实现Queue. 递归和栈实现逆序操作一个栈. 仅用一个栈排序另一个栈. 打印两个有序链表的公共部分. 删除...

    recommended-problems

    https://leetcode.com/problems/merge-two-sorted-lists/ 2D阵列 https://leetcode.com/problems/spiral-matrix/ https://leetcode.com/problems/search-a-2d-matrix/ ...

    leetcode答案-LeetCode:Swift中的LeetCode

    leetcode 答案LeetCode LeetCode in Swift 这个Repo 用来存下我在LeetCode 解题的原始档,包含解题中遇到的错误,也包含解出AC 的答案, 以下的清单将连结到我的Github Pages 中,皆有题目中文翻译与解题的过程。...

    leetcode2-Leetcode:Leetcode_answer

    leetcode 2 Leetcode答案集 关于项目: 本项目包含本人LeetCode解题的答案,全部将由JavaScript语言进行解答。并会在每个题目的文件夹中添加相关的思路解析。 详情 # Title Solution Time Space Difficulty 1 Two ...

    leetcode添加元素使和等于-leetcode:我的leetcode解决方案

    leetcode添加元素使和等于 经验教训 一定要吧功能尽量细化为函数,这样一者做题思路比较清晰,二者可以在某些情况下直接return值。 如果输入的形式是一个序列,则可以想想:分治、动规、贪婪,一般不建议搜索,因为...

    leetcode被墙-leetcode:leetcode笔记

    easy:21.Merge_Two_Sorted_Lists return a or b 首先我是第一次见到这种写法,查看了官方文档,引用如下: The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is ev

    多线程leetcode-leetcode-java:leetcode上的题解,基于java语言

    多线程 leetcode 前言 每天刷点leetcode,基于java语言实现。 leetcode上难度分三档:easy,medium,hard. 如下: easy medium ...Merge k Sorted Lists Reverse Nodes in k-Group Trapping Rain Water

    leetcode2sumc-LeetCode:LeetCode的一些题目

    leetcode 2 sum c LeetCode 帮助文档 帮助文档存放在Help文件夹下。 文件名 文件描述 链接 complexitypython.txt Python的一些常规操作的复杂度统计 题目清单 Array(数组) ID Difficulty Title Java Python 1 Easy ...

    leetcode中文版-LeetCode:LeetcodeC++/Java

    leetcode中文版 LeetCode # Title Chinese Tag Solution 1 Two Sum 两数之和 array,hash 2 Add Two Numbers 两数相加 math 3 Longest Substring Without Repeating Characters 无重复字符的最长子串 string 4 ...

Global site tag (gtag.js) - Google Analytics