0
点赞
收藏
分享

微信扫一扫

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

蚁族的乐土 2022-05-04 阅读 113

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

举报

相关推荐

0 条评论