
就是你知道B了,返回一个重新排序的A (能一 一对应比B把的数组)

思路:首先对A 和B进行排序,然后从A中拿出最小的和B最小的进行比较,如果还是比B小,那么就把A的那个元素丢进右边的队列中去。如果取出的A比B大,那么就在B的旁边存进列表(可以用Map模拟)中去:
public static void main(String[] args) {
//如果现在A和B一一比较,那么A比B小三个,输了
/* int[] A=new int[]{10,24,8,32};
int[] B=new int[]{13,25,25,11};*/
int[] B=new int[]{2,9,11};
int[] A=new int[]{16,1,9};
//现在返回进过我们的算法对A进行排序,那么A就和B平局了
System.out.println(Arrays.toString(advantageCount(A,B)));
}
public static int[] advantageCount(int[] A,int[] B){
int[] sortB=B.clone();
Arrays.sort(sortB);
Arrays.sort(A);
//左边的队列 先初始化
Map<Integer,Deque<Integer>> bMap=new HashMap<>();
//先保留B的原顺序
for (int b : B) {
bMap.put(b,new LinkedList<>());
}
//右边的垃圾队列
Deque<Integer> aq=new LinkedList<>();
int j=0;
for (int a : A) {
if (a> sortB[j]){
bMap.get(sortB[j++]).add(a);
}else {
aq.add(a);
}
}
//返回的数组
int[] ans=new int[A.length];
for (int i = 0; i < B.length; i++) {
if (bMap.get(B[i]).size()>0){
//从左边列表取出最后一个值
ans[i]=bMap.get(B[i]).removeLast();
}else {
//如果左边没有 那么就从右边队列随便给它一个
ans[i]=aq.removeLast();
}
}
return ans;
}
468

被折叠的 条评论
为什么被折叠?



