• leetcode第22题--Merge k Sorted Lists


    problem:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

    先合并两个list,再根据归并排序的方法递归合并。假设总共有k个list,每个list的最大长度是n,那么运行时间满足递推式T(k) = 2T(k/2)+O(n*k)。根据主定理,可以算出算法的总复杂度是O(nklogk)。空间复杂度的话是递归栈的大小O(logk)。

    
    
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) // 将两个list  merge
    {
        if(!l1)
            return l2;
        if(!l2)
            return l1;
        ListNode *tmp = new ListNode(0);
        ListNode *ans = tmp;
        while(l1 && l2)
        {
            if(l1 -> val < l2 -> val)
            {
                ans -> next = l1;
                ans = ans -> next;
                l1 = l1 -> next;
            }
            else
            {
                ans -> next = l2;
                ans = ans -> next;
                l2 = l2 -> next;
            }
        }
        if (l1)
        {
            while(l1)
            {
                ans -> next = l1;
                ans = ans -> next;
                l1 = l1 -> next;
            }
        }
    
        if (l2)
        {
            while(l2)
            {
                ans -> next = l2;
                ans = ans -> next;
                l2 = l2 -> next;
            }
        }
        ans = tmp;
        delete ans;
        return tmp -> next;
    }
    ListNode *reMerge(vector<ListNode *> &lists, int l, int r)
    {
        if(l < r) // 类似于归并排序,把一大块分成l和r两块,然后将两个合并(l和r也还可以再分)
        {
            int m = (l + r)/2;
            return mergeTwoLists(reMerge(lists, l, m), reMerge(lists, m + 1, r));
        }
        else
            return lists[l];
    }
    ListNode *mergeKLists(vector<ListNode *> &lists)
    {
        ListNode *ans = NULL;// 用NULL 而不是利用 new ListNode(0)
        if (lists.size() == 0)
            return ans;
        return reMerge(lists, 0, lists.size() - 1);
    }
    };
    
    
    
     
  • 相关阅读:
    关于typedef在struct使用上的一些问题
    软件工程--趣盒--第四次团队作业--软件实现与测试
    趣盒——快速入门手册
    软件工程趣盒软件设计
    软件工程项目需求分析
    在VS2017下配置OpenGL
    破阵子青铜团队介绍以及项目背景介绍
    海客谈瀛洲,烟涛微茫信难求——微信
    第一次作业:扑通扑通 我的IT
    5.线性回归算法
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4036321.html
Copyright © 2020-2023  润新知