给出两个数组,求出A数组的一个排列,使下标相同的对应数有尽量多的数满足A[i] > B[i]
这不就是田忌赛马嘛!
我们使用贪心的策略
如果田忌最快的马比对方最快的马快,就和他比,赢一场
否则就用田忌最慢的马去和对方最快的马去比
这个题目要输出排列,可以看下代码:
public int[] advantageCount(int[] A, int[] B) {
int len = A.length;
Arrays.sort(A);
//递减的一个优先队列
int[] res = new int[len];
Queue<int[]> q = new PriorityQueue<>((o1, o2) -> Integer.compare(o2[0], o1[0]));
for (int i = 0; i < len; i++) q.add(new int[]{B[i], i});
int l = 0, r = len - 1;
while(!q.isEmpty()) {
int[] poll = q.poll();
int v = poll[0];
int idx = poll[1];
if (A[r] > v) {
res[idx] = A[r];
r--;
} else {
res[idx] = A[l];
l++;
}
}
return res;
}
还有一种贪心的策略: 找到比对方的马快的最小的那个马
https://leetcode.com/problems/advantage-shuffle/discuss/149840/C%2B%2BJava-Greedy-Solution-Using-Map
主要学习一下treemap的用法
public int[] advantageCount(int[] A, int[] B) {
TreeMap<Integer, Integer> m = new TreeMap<>();
for (int i : A) m.put(i, m.getOrDefault(i, 0) + 1);
int[] res = new int[A.length];
for (int i = 0; i < A.length; ++i) {
Integer x = m.higherKey(B[i]);
if (x == null) x = m.firstKey();
m.put(x, m.get(x) - 1);
if (m.get(x) == 0) m.remove(x);
res[i] = x;
}
return res;
}