• [LeetCode 题解]: Merge k Sorted Lists


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

    题意:对k个有序的链表进行归并排序。并分析其复杂度。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* merge(ListNode* left, ListNode* right){   //归并操作
            if(left==NULL) return right;
            if(right==NULL) return left;
            ListNode *ans =new ListNode(0);
            if(left->val <= right->val){
                ans=left;
                left = left->next;    
            }else{
                ans=right;
                right=right->next;
            }
            ans->next = merge(left,right);
            return ans;
        }
        ListNode* mergesort(vector<ListNode *> &lists,int left,int right){  //devide && conquer
            if(left>right){
                return NULL;
            }if(left==right){
                return lists[left];
            }else{
                int middle = (left+right)>>1;
                ListNode *lleft = mergesort(lists,left,middle);
                ListNode *lright = mergesort(lists,middle+1,right);
                return merge(lleft,lright);
            }
            
        }
        ListNode *mergeKLists(vector<ListNode *> &lists) {
            int left =0,right =lists.size()-1;
            int middle= (left+right)>>1;
            ListNode *lleft = mergesort(lists,left,middle);
            ListNode *lright = mergesort(lists,middle+1,right);
            return merge(lleft,lright);
        }
    };

    时间复杂度: O(n*logn) 

    空间复杂度: O(1)

    至于具体的量化分析呢,呵呵。。。数学推导了

    转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢!

  • 相关阅读:
    前端-JavaScript
    前端-HTML
    Python源程序(.py)转换为可执行文件(.exe)
    进程
    算法之动态规划问题
    算法之斐波那契数列
    贪心算法找零问题
    算法之迷宫问题
    数据结构相关知识
    常用排序算法
  • 原文地址:https://www.cnblogs.com/double-win/p/3873952.html
Copyright © 2020-2023  润新知