zoukankan      html  css  js  c++  java
  • 23. Merge k Sorted Lists

    合并k个有序列表。

    (1)堆排序

    bool cmp(ListNode *l1,ListNode *l2){
        return l1->val > l2->val;
     }
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            vector<ListNode*> validLists;
            for(auto i:lists)
                if(i) validLists.push_back(i);
            ListNode *pre = new ListNode(-1);
            ListNode *curr = pre;
            make_heap(validLists.begin(),validLists.end(),cmp);
            while(!validLists.empty()){
                ListNode *top = validLists.front();
                pop_heap(validLists.begin(),validLists.end(),cmp);
                validLists.pop_back();
                curr->next = top;
                curr = curr->next;
                top = top->next;
                if(top){
                    validLists.push_back(top);
                    push_heap(validLists.begin(),validLists.end(),cmp);
                }
            }
            return pre->next;
        }
    };

    (2)两两合并

    //merge two lists recursive version
    
    //time complexity: O(klogk)
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            if (lists.size() == 0) return NULL;
            int n = lists.size();
            return merge(lists, 0, n - 1);
        }
    
        ListNode * merge(vector<ListNode *>& lists, int begin, int end) {
            if (begin > end) return NULL;
            if (begin == end) return lists[begin];
            if (begin + 1 == end) return mergeTwoList(lists[begin], lists[end]);
            int mid = begin + (end - begin) / 2;
            ListNode * firstHalf = merge(lists, begin, mid);
            ListNode * secondHalf = merge(lists, mid + 1, end);
            return mergeTwoList(firstHalf, secondHalf);
        }
    
        ListNode* mergeTwoList(ListNode* l1, ListNode* l2) {
            if (l1 == NULL) return l2;
            if (l2 == NULL) return l1;
            if (l1->val < l2->val) {
                ListNode * head = l1;
                head->next = mergeTwoList(l1->next, l2);
                return head;
            } else {
                ListNode * head = l2;
                head->next = mergeTwoList(l1, l2->next);
                return head;
            }
        }
    };
  • 相关阅读:
    Redis:五、Redis持久化
    Redis:四、jedis连接redis服务器
    Redis:三、Key和Value
    php 拆分的 string里包含“2”或“1”符号(“”或者“”)
    清除float浮动
    js 判断数据类型
    form表单里target属性(在新窗口打开页面)
    think PHP5实现文件下载
    echarts自定义提示框内容
    Chrome浏览器不支持小于12px的字体大小
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5239438.html
Copyright © 2011-2022 走看看