题目链接
    image.png
    image.png

    1. class Solution {
    2. public int[] advantageCount(int[] nums1, int[] nums2) {
    3. // 1. 对两个数组进行排序,但是nums2数组需要保留原样
    4. Arrays.sort(nums1);
    5. int[] sortB = nums2.clone();
    6. Arrays.sort(sortB);
    7. // 保存对应的最大化的下标值
    8. Map<Integer, Deque<Integer>> map = new HashMap<>();
    9. Deque<Integer> aq = new LinkedList<>();
    10. for(int b : sortB) {
    11. map.put(b, new LinkedList<>());
    12. }
    13. int i = 0;
    14. for(int a : nums1) {
    15. if(a > sortB[i]) {
    16. map.get(sortB[i++]).offer(a);
    17. } else {
    18. aq.offer(a);
    19. }
    20. }
    21. int[] ans = new int[nums2.length];
    22. // 处理B中对应的优势最大化的下标
    23. for(int j = 0; j < nums2.length; j++) {
    24. Deque<Integer> d = map.get(nums2[j]);
    25. if(d.size() == 0) {
    26. ans[j] = aq.removeLast();
    27. } else {
    28. ans[j] = d.removeLast();
    29. }
    30. }
    31. return ans;
    32. }
    33. }