LeetCode[One hard A Day] - Merge K Sorted Lists

Merge K Sorted Lists

写一个helper function用来merge two sorted lists (O(N), N 为number of nodes in the two lists)

总的function只要每两个lists call一下helper function就行了 (O(N logk), k 为number of lists)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeT(ListNode* l1, ListNode* l2){
        ListNode* res = new ListNode(0);
        ListNode* temp = res;
        while(l1!=NULL && l2!=NULL){
            if(l1->val<=l2->val){
                temp->next = l1;
                l1 = l1->next;
                temp = temp->next;
            }
            else{
                temp->next = l2;
                l2 = l2->next;
                temp = temp->next;
                
            }
        }
        if(l1!=NULL){
            temp->next = l1;
        }
        if(l2!=NULL){
            temp->next = l2;
        }
        return res->next;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int len = lists.size();
        if(len==0) return NULL;
        if(len==1) return lists[0];

        vector<ListNode*> res;
        for(int i=1; i<lists.size();i+=2){
            res.insert(res.begin(), mergeT(lists[i-1], lists[i]));
        }
        if(len%2==1) res.insert(res.begin(), lists[len-1]);
        return mergeKLists(res);

    }
};

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/79784508