Tian Ji Horse Racing Java

Given two equal-sized arrays A and B, the advantage of A over B can be described by the number of indexes that satisfy Ai] > Bi].
Return any permutation of A that maximizes its advantage over B.

In fact, the core idea is to make the number in A the smallest and just larger than the number in B. We can use a linked list to store the corresponding data in A and B. As for the data in B that is larger than all the numbers in A, it will match the remaining numbers in A. digits (you can match them as you like).

The following is the specific implementation code:

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;
    }

}

Output result: Tian Ji’s horse racing result is: [14, 11, 19, 9, 17, 13]

[Likou Algorithm Question] Advantage Shuffle (Tian Ji Horse Racing) - Greedy_bilibili_bilibili

Supongo que te gusta

Origin blog.csdn.net/wfdfg/article/details/133280976
Recomendado
Clasificación