zoukankan      html  css  js  c++  java
  • Merge k Sorted Lists 分类: Leetcode(树) 2015-04-09 09:35 17人阅读 评论(0) 收藏

    Merge k Sorted Lists

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


    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *merge2List(ListNode *h1, ListNode *h2) {
            ListNode dummy(-1);
            ListNode *tail = &dummy;
            while( h1 && h2) {
                if(h1->val > h2->val) {
                    tail->next = h2;
                    h2 = h2->next;
                } else {
                    tail->next =h1;
                    h1 = h1->next;
                }
                tail = tail->next;
            }
            
            if(h1) tail->next = h1;
            if(h2) tail->next = h2;
            return dummy.next;
        }
    
        ListNode *sort(int start, int len, vector<ListNode*> &lists) {
            if(!len) return nullptr;
            if(len == 1) return lists[start];
            ListNode *h1 = sort(start, len/2,lists);
            ListNode *h2 = sort(start+len/2, len -len/2,lists);
            return merge2List(h1,h2);
        }
    
        ListNode *mergeKLists(vector<ListNode *> &lists) {
            return sort(0, lists.size(),lists);
        }
    
    };





    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    树上莫队 SPOJ COT2
    UVA 11478(差分约束 + 二分)
    可图的度序列判断与构造
    Codeforces Round #306 (Div. 2) 550A Two Substrings
    UVA 11300 分金币
    HDU 2546 饭卡(01 背包)
    hdu 1142 最短路+记忆化
    codeforces ice cave
    codeforces school mark(贪心)
    JavaScript函数
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656942.html
Copyright © 2011-2022 走看看