Why and where my 15 lines code cost 35ms?

  • 0

    Hi everyone,
    I'm trying to improve my code's performance, the code below cost about 35ms for 1562 test case.
    NOTE: Each time I submit the same code it presents different cost time =_=!, sometimes up to 59ms, and 35ms is the shortest time.
    Please point out why and where my code cost so much time.

     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) 
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        struct ListNode* result = l1;
        int sum = l1->val + l2->val; 
        l1->val = sum % 10;
        struct ListNode* l2next = l2->next;
        if (sum / 10) 
            l2->val = 1;
            l2->next = NULL;
            l1->next = addTwoNumbers(l1->next, l2);
        l1->next = addTwoNumbers(l1->next, l2next);
        return result;

  • 0

    The code I paste above save the results into l1(just to avoid calling the malloc), and where there's a carry flag(sum /10 != 0), i use the l2(which is useless) to store the carry value, also just for saving time by not calling the malloc.

Log in to reply

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