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;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:51
点赞 评论 收藏
分享
投递拓竹科技等公司10个岗位
点赞 评论 收藏
分享
07-11 22:27
中南大学 Java
程序员牛肉:学历的话没问题。但是没问题的也就只有学历了。 其实你的整体架构是正确的,博客接着干。但是项目有点过于简单了。从后端的角度上讲,你这也就是刚入门的水平,所以肯定约面试够呛。 如果你要应聘后端岗位,那你第一个项目竟然是仿写操作系统。这个你要面试官咋问你。你一定要记住一点,你简历上写的所有的东西,都是为了证明你有能力胜任当前的岗位,而不是为了证明你自己会什么。 如果你只是浅浅的做几个项目,描述也都是烂大街。技术点也都是各种混水类的配置类需求,那你就不要幻想自己能走多远。一定要保持思考,保持学习。
点赞 评论 收藏
分享
06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务