LeetCode-870. Advantage Shuffle [C++][Java]

这篇博客介绍了如何解决LeetCode上的870题——优势洗牌。通过使用C++和Java两种语言,博主展示了如何找到使nums1相对于nums2具有最大优势的排列。C++解决方案利用了multiset容器,而Java解决方案则运用了优先队列。这两个方法都有效地找到了满足条件的数组 nums1 的排列。
摘要由CSDN通过智能技术生成

LeetCode-870. Advantage Shufflehttps://leetcode.com/problems/advantage-shuffle/

You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].

Return any permutation of nums1 that maximizes its advantage with respect to nums2.

Example 1:

Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11]
Output: [2,11,7,15]

Example 2:

Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11]
Output: [24,32,8,12]

Constraints:

  • 1 <= nums1.length <= 10^5
  • nums2.length == nums1.length
  • 0 <= nums1[i], nums2[i] <= 10^9

【C++】

class Solution {
public:
    vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
        multiset<int> t;
        for (auto num : nums1) {t.insert(num);}
        vector<int> ans;
        for (auto num : nums2) {
            auto upper = t.upper_bound(num);
            if (upper != t.end()) {
                ans.push_back(*upper);
                t.erase(upper);
            } else {
                ans.push_back(*t.begin());
                t.erase(t.begin());
            }
        }
        return ans;
    }
};

【Java】

class Solution {
    public int[] advantageCount(int[] nums1, int[] nums2) {
        PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> nums2[b]-nums2[a]);
        for (int i=0; i<nums2.length; i++) {pq.add(i);}
        Arrays.sort(nums1);
        int left = 0;
        int right = nums1.length - 1;
        int v[] = new int[nums1.length];
        while (!pq.isEmpty()){
            int index = pq.poll();
            if (nums1[right] > nums2[index]){
                v[index] = nums1[right--];
            } else {
                v[index]=nums1[left++];
            }
        }
        return v;
    }
}

参考文献

【1】multiset用法总结_二喵君的博客-CSDN博客_multiset

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值