友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
  | 
  | 
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

公众号的微信号是: jikerizhi。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 | 
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 
思路分析
- 
一刷
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-08-16 20:44:53
 */
public int[] advantageCount(int[] nums1, int[] nums2) {
  // idx 中存的就是每个 nums2 数组中对应的下标
  Integer[] idx = new Integer[nums2.length];
  for (int i = 0; i < nums2.length; i++) {
    idx[i] = i;
  }
  // 利用 nums2 中数字的大小,对下标进行排序
  // 这样可以保持 nums2 数字不变的情况下,对其数字进行排序。
  Arrays.sort(idx, Comparator.comparingInt(i -> nums2[i]));
  Arrays.sort(nums1);
  int left = 0, right = nums1.length - 1;
  int[] result = new int[nums1.length];
  for (int i = nums2.length - 1; i >= 0; i--) {
    int num = nums2[idx[i]];
    if (num < nums1[right]) {
      // nums1 能赢就直接上
      result[idx[i]] = nums1[right];
      right--;
    } else {
      // nums1 不能赢就选最小值当炮灰
      result[idx[i]] = nums1[left];
      left++;
    }
  }
  return result;
}

