[LeetCode 2] Add Two Numbers

Man, this problem looks simple from the name, but it nearly killed me. The idea is clear, but the implementation was painful. My fundamentals really need work – it took forever.

The problem says: given two non-negative linked lists, add the corresponding values of the two lists. If the sum is 10 or greater, there’s a carry – and the carry is what really tripped me up. Got WA once because of it.

One thing to note is that the numbers need to be reversed. I directly reversed both input linked lists, which led to AC. If you miss this, you’ll likely get wrong answers. But reversing a linked list really frustrated me – I need to practice my fundamentals more.

There’s also the issue of deep copy vs. shallow copy with pointers.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int sum = m + n;
        if (sum % 2 == 0) {
            return (findk(A, m, B, n, sum/2) + findk(A, m, B, n, sum/2 + 1)) / 2;
        } else {
            return findk(A, m, B, n, sum/2 + 1);
        }
    }

    double findk(int A[], int m, int B[], int n, int k) {
        if (m > n) {
            return findk(B, n, A, m, k);
        }
        if (m <= 0)
            return B[k-1];
        if (n <= 0)
            return A[k-1];
        if (k == 1) {
            if (A[0] < B[0])
                return A[0];
            else
                return B[0];
        }

        int a = k/2;
        if (m < k/2)
            a = m;
        int b = k - a;
        if (A[a-1] == B[b-1])
            return A[a-1];
        else if (A[a-1] < B[b-1]) {
            return findk(A + a, m - a, B, n, k - a);
        } else {
            return findk(A, m, B + b, n - b, k - b);
        }
    }
};