870. 优势洗牌

发布时间:2022-06-27 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了870. 优势洗牌脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 A[i] > B[i] 的索引 i 的数目来描述。

返回 A 的任意排列,使其相对于 B 的优势最大化

:力扣(LeetCode) 链接:https://leetcode-cn.COM/PRoblems/advantage-shuffle 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

有序表

import java.util.Comparator;
import java.util.TreeSet;

class Solution {
    public int[] advantageCount(int[] nums1, int[] nums2) {
        TreeSet<int[]> set = new TreeSet<>(new Comparator<int[]>() {
            @override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0]) {
                    return Integer.compare(o1[1], o2[1]);
                }
                return Integer.compare(o1[0], o2[0]);
            }
        });
        for (int i = 0; i < nums1.length; ++i) {
            set.add(new int[]{nums1[i], i});
        }

        int[] ret = new int[nums1.length];

        for (int i = 0; i < nums2.length; ++i) {
            int[] floor = set.ceiling(new int[]{nums2[i] + 1, 0});
            if (floor == null) {
                floor = set.First();
            }
            ret[i] = floor[0];
            set.remove(floor);
        }
        return ret;
    }
}

排序 + 贪心

import java.util.*;

class Solution {
    public int[] advantageCount(int[] A, int[] B) {
        int[] sortedA = A.clone();
        Arrays.sort(sortedA);
        int[] sortedB = B.clone();
        Arrays.sort(sortedB);

        // assigned[b] = list of a that are assigned to beat b
        Map<Integer, Deque<Integer>> assigned = new HashMap();
        for (int b: B) assigned.put(b, new LinkedList());

        // remaining = list of a that are not assigned to any b
        Deque<Integer> remaining = new LinkedList();

        // populate (assigned, remaining) appropriately
        // sortedB[j] is always the smallest unassigned element in B
        int j = 0;
        for (int a: sortedA) {
            if (a > sortedB[j]) {
                assigned.get(sortedB[j++]).add(a);
            } else {
                remaining.add(a);
            }
        }

        // Reconstruct the answer From annotations (assigned, remaining)
        int[] ans = new int[B.length];
        for (int i = 0; i < B.length; ++i) {
            // if there is some a assigned to b...
            if (assigned.get(B[i]).size() > 0)
                ans[i] = assigned.get(B[i]).pop();
            else
                ans[i] = remaining.pop();
        }
        return ans;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的870. 优势洗牌全部内容,希望文章能够帮你解决870. 优势洗牌所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。