• leetcode888


    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;        
        }
    };
  • 相关阅读:
    css的书写位置+元素分类
    选择器
    我的js运动库新
    js的相关距离
    关于小乌龟的使用
    linux 基础
    linux shell快捷操作【超级实用】
    算法面试常见问题【转】
    http://www.cnblogs.com/zhangchaoyang/archive/2012/08/28/2660929.html
    cocos2dx + vs安装使用
  • 原文地址:https://www.cnblogs.com/asenyang/p/9724957.html
Copyright © 2020-2023  润新知