首页 » 编程之美 » 正文

[leetcode_2]Add Two Numbers

我擦这个题看名字挺简单的。其实思路很清晰,但是真的憋死了我快。基本功真拙计,写了好久。
题目的意思是说给你两个非负的链表,以此对这两个链表的的相应值求和,如果和大于10会[进位]~进位真心蛋疼,在这个地方WA了一次。
题目中有个需要注意的是需要逆序,我对读入的两个链表直接逆序了。所以AC了。如果不注意,可能真心会出错,不过链表逆序真心憋死我了。好好练练基本功还是需要[leetcode_4]Add Two Numbers。
还有指针的深拷贝浅拷贝问题。

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);<br />
        }
        if(m &lt;= 0)
            return B[k-1];
        if(n &lt;= 0)
            return A[k-1];
        if(k == 1)
        {
            if(A[0] &lt; B[0])
                return A[0];
            else
                return B[0];
        }
        int a = k/2;
        if(m &lt; k/2)
            a = m;
        int b = k -a;
        if(A[a-1] == B[b-1])return A[a-1];
        else
            if(A[a-1] &lt; B[b-1])
            {
                return findk(A+a,m-a,B,n,k-a);<br />
            }
            else
                if(A[a-1] &gt; B[b-1])
                {
                    return findk(A,m,B+b,n-b,k-b);
                }</p>

<pre><code>}
</code></pre>

<p>};

发表评论