class Solution {
public:
    int Binary_Search(vector<int> x, int N, int keyword)
    {
        int low = 0, high = N - 1, mid;
        while (low <= high)
        {
            mid = (low + high) / 2;
            if (x[mid] == keyword)
                return mid;
            if (x[mid] < keyword)
                low = mid + 1;
            else
                high = mid - 1;

        }
        return -1;
    }

    vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
        int sumA = 0;
        for (auto a : A)
        {
            sumA += a;
        }

        int sumB = 0;
        for (auto b : B)
        {
            sumB += b;
        }
        sort(A.begin(), A.end());
        sort(B.begin(), B.end());
        int sum = sumA + sumB;//8 = 3 + 5
        int mid = sum / 2;//4 = 8 / 2
        vector<int> V;
        if (sumA == sumB)
        {
            V.push_back(0);
            V.push_back(0);            
        }
        else if (sumA < sumB)
        {
            int diff = mid - sumA;//1 =  4 - 3
            for (auto a : A)
            {
                int attemptB = a + diff;//b =a + diff
                int positionB = Binary_Search(B, B.size(), attemptB);
                if (positionB != -1)
                {
                    V.push_back(a);
                    V.push_back(B[positionB]);
                    break;
                }
            }
        }
        else//sumA>sumB
        {
            int diff = mid - sumB;
            for (auto b : B)
            {
                int attemptA = b + diff;
                int positionA = Binary_Search(A, A.size(), attemptA);
                if (positionA != -1)
                {
                    V.push_back(A[positionA]);
                    V.push_back(b);
                    break;
                }
            }
        }

        return V;        
    }
};

 

posted on 2018-09-29 17:35  Sempron2800+  阅读(127)  评论(0编辑  收藏  举报