LeetCode: 870. Advantage Shuffle

LeetCode: 870. Advantage Shuffle

题目描述

Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i].
Return any permutation of A that maximizes its advantage with respect to B.

Example 1:

Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15]

Example 2:

Input: A = [12,24,8,32], B = [13,25,32,11]
Output: [24,32,8,12]

Note:

1 <= A.length = B.length <= 10000
0 <= A[i] <= 10^9
0 <= B[i] <= 10^9

解题思路

B 数组中的每个数字找到与之对应 A 数组中大于它的最小值,如果没有则将其设为 A 数组中没处理数据的最小值。

AC 代码

class Solution {
public:
    vector<int> advantageCount(vector<int>& A, vector<int>& B) {
        vector<int> ans;
        map<int, int> numsACount;
        for(int i = 0; i < A.size(); ++i)
        {
            ++numsACount[A[i]];
        }

        // 依次填入最小的数
        for(size_t i = 0; i < B.size(); ++i)
        {
            int curNum = 0;
            auto iter = numsACount.upper_bound(B[i]);

            if(iter != numsACount.end())
            {
                curNum = iter->first;
            }
            else
            {
                curNum = numsACount.begin()->first;
            }

            --numsACount[curNum];
            if(numsACount[curNum] == 0) numsACount.erase(curNum);
            ans.push_back(curNum);
        }

        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/yanglingwell/article/details/81053126