田忌赛马Java

给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 Ai] > Bi] 的索的数目来描述。
返回 A的任意排列,使其相对于 B 的优势最大化.

其实核心思想就是让A中的数最小且刚好大于B中数,我们可以用链表来存储A和B中对应的数据,至于B比A中所有的数都大的数据,则匹配我们A中剩余的数字即可(随意匹配即可).

下面是具体实现的代码:

package test;

import java.util.*;

public class Algorithm {
    public static void main(String[] args) {
        int[] advantage = advantage(new int[]{9, 17, 19, 11, 13, 14}, new int[]{21, 10, 16, 20, 16, 12});
        System.out.println("田忌赛马结果是:" +Arrays.toString(advantage));
    }

    //田忌赛马
    public static int[] advantage(int[] A, int[] B) {
        int[] bclone = B.clone();
        Arrays.sort(bclone);
        Arrays.sort(A);
        Map<Integer, Deque<Integer>> bMap = new HashMap<>();
        for (int b : B) {
            bMap.put(b, new LinkedList<>());
        }
        Deque<Integer> aDeque = new LinkedList<>();
        int j = 0;
        for (int a : A) {
            if (a > bclone[j]) {
                bMap.get(bclone[j]).add(a);
                j++;
            } else {
                aDeque.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] = aDeque.removeLast();
            }
        }
        return ans;
    }

}

输出结果:田忌赛马结果是:[14, 11, 19, 9, 17, 13]

【力扣算法题】优势洗牌(田忌赛马)-贪心_哔哩哔哩_bilibili

猜你喜欢

转载自blog.csdn.net/wfdfg/article/details/133280976