Merge k Sorted Lists ’s solution show Memory Limit Exceeded error


  • 0
    W

    My Solution works well on my Mac Xcode project.
    But always show Memory Limit Exceeded on leetcode. can someone tell me why

     ListNode *mergeKLists(vector<ListNode *> &lists) {
    if (lists.size() < 2) {
        return lists.size() == 0 ? nullptr: lists.back();
    }
    
    return helper(lists, 0, int (lists.size() - 1));}
    
    ListNode *helper(vector<ListNode *> lists, int l, int r) {
    if(l<r)
    {
        int m = (l+r)/2;
        return mergeTwoLists(helper(lists,l,m),helper(lists,m+1,r));
    }
    return lists[l];}
    
    ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) {
    if (l1 == nullptr) {
        return l2;
    } else if (l2 == nullptr) {
        return l1;
    }
    ListNode * head = l1;
    ListNode * point1 = l1;
    ListNode * point2 = l2;
    if (l1->val > l2->val) {
        point1 = l2;
        point2 = l1;
        head = l2;
    }
    while (point2 != nullptr) {
        if (point1->next == nullptr) {
            point1->next = point2;
            break;
        } else {
            while (point1->next != nullptr) {
                if (point1->val <= point2->val && point1->next->val > point2->val) {
                    ListNode* tmp1 = point1->next;
                    ListNode* tmp2 = point2->next;
                    point1->next = point2;
                    point2->next = tmp1;
                    point1 = point2;
                    point2 = tmp2;
                    break;
                }
                point1 = point1->next;
            }
        }
    }
    
    return head;}

Log in to reply
 

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