给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 A[i] > B[i] 的索引 i 的数目来描述。
返回 A 的任意排列,使其相对于 B 的优势最大化。
public static int[] advantageCount(int[] A, int[] B) {int[] sortedA = A.clone();Arrays.sort(sortedA);//找一个代价最小的去匹配B中的,比B大,在A中又是最小的int[] sortedB = B.clone();Arrays.sort(sortedB);//避免比较时,A每次都要重头遍历Map<Integer, Deque<Integer>> assigned = new HashMap();for (int b : B)assigned.put(b, new LinkedList());Deque<Integer> remaining = new LinkedList();int j = 0;for (int a : sortedA) {if (a > sortedB[j]) {assigned.get(sortedB[j++]).add(a);} else {remaining.add(a);}}int[] ans = new int[B.length];for (int i = 0; i < B.length; ++i) {if (assigned.get(B[i]).size() > 0) {ans[i] = assigned.get(B[i]).removeLast();} else {ans[i] = remaining.removeLast();}}return ans;}
时间复杂度:O(N log N),其中 N 是 A 和 B 的长度。
空间复杂度:O(N)。
