Why the same code C run 4ms while cpp run 8ms


  • 0
    D

    C version:

    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
            struct ListNode* l = l1,* r = l2,* m = NULL,* c = NULL,* pre = NULL;
            if(!l1 && l2)
                return l2;
            if(l1 && !l2)
                return l1;
            if(!l1 && !l2)
                return NULL;
            while(l && r)
            {
                if(c)
                    pre = c;
                if(l->val <= r->val)
                {
                    c = l;
                    l = l->next;
                }
                else
                {
                    c = r;
                    r = r->next;
                }
                if(!m)
                    m = c;
                if(pre)
                    pre->next = c;
            }
            
            if(l)
                c->next = l;
            if(r)
                c->next = r;
            return m;
    }
    

    cpp version:

    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode* l = l1;
            ListNode* r = l2;
            ListNode* m = nullptr;
            ListNode* c = nullptr;
            ListNode* pre = nullptr;
            if(!l1 && l2)
                return l2;
            if(l1 && !l2)
                return l1;
            if(!l1 && !l2)
                return nullptr;
            while(l && r)
            {
                if(c)
                    pre = c;
                if(l->val <= r->val)
                {
                    c = l;
                    l = l->next;
                }
                else
                {
                    c = r;
                    r = r->next;
                }
                if(!m)
                    m = c;
                if(pre)
                    pre->next = c;
            }
            
            if(l)
                c->next = l;
            if(r)
                c->next = r;
            return m;
        }
    };

  • 1
    A

    run-time environments takes different time ,Solution::mergeTwoLists is not static, caller had to pass this pointer to it


Log in to reply
 

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