P50-优势洗牌(田忌赛马)-贪心
//优势洗牌(田忌赛马)-贪心 /* * 给定两个大小相同的数值A和B,A相对于B的优势可以用满足A[i]>B[i]的索引i的数目来描述 * 返回A的任意排列,使其相对于B的优势最大化 * * A>B的数量的最大化 * */ /* * 如果A中没有一个数大于B中的一个数,就用A的最小值来抵消 * 如果A中有多个数大于B中的一个数,就用这多个数中最小的来抵消 * */ public class P50 { public static void main(String[] args) { int[] a = new int[]{10,24,8,32}; int[] b = new int[]{13,25,25,11}; System.out.println(Arrays.toString(advantageCount(a, b))); } public static int[] advantageCount(int[] a, int[] b){ int[] sortB = b.clone(); //不破坏b数组 Arrays.sort(sortB); Arrays.sort(a); Map<Integer, Deque<Integer>> bMap = new HashMap<>(); for(int item : b){ bMap.put(item, new LinkedList<>()); } Deque<Integer> aq = new LinkedList<>(); //a的队列 int j=0; for(int item : a){ if(item > sortB[j]){ bMap.get(sortB[j]).add(item); //b的j马的对手是a的item马 j++; }else{ aq.add(item); //a的马比不上b的马,做后备 } } 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; } }