Surprised that my solution beats 100.00% cpp submissions


  • 0
    C

    so i post my code

    class Solution {
    public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        vector<ListNode*>::iterator iter = lists.begin();
        return mergeKLists(iter,lists.size());
    }
    
    private:
    ListNode* mergeKLists(vector<ListNode*>::iterator iter, int n) {
        if(n==0) return NULL;
        if(n==1) return *iter;
        return mergeTwoLists(mergeKLists(iter,(n+1)/2), mergeKLists(iter+(n+1)/2,n/2));
    }
    
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1) return l2;
        if(!l2) return l1;
        ListNode* result = NULL;
        if(l1->val<l2->val) {
            result = l1;
            l1 = l1->next;
        }
        else {
            result = l2;
            l2 = l2->next;
        }
        ListNode* head = result;
        while(l1&&l2) {
            if(l1->val<l2->val) {
                head->next = l1;
                l1 = l1->next;
            }
            else {
                head->next = l2;
                l2 = l2->next;
            }
            head = head->next;
        }
        if(l1) head->next = l1;
        else head->next = l2;
        return result;
    }
    

    };


  • 0
    U

    really simple and elegant, great!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.