• 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;        
        }
    };
  • 相关阅读:
    Spark RDD 创建(一)
    编译Spark-1.6.0源码
    Strom学习笔记一
    Hbase笔记——RowKey设计
    Hbase物理模型
    HDFS分布式文件系统设计思想
    Hbase 基本命令
    内部排序算法
    278. First Bad Version
    266. Palindrome Permutation
  • 原文地址:https://www.cnblogs.com/asenyang/p/9724957.html
Copyright © 2020-2023  润新知