package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/advantage-shuffle/
 */
public class Problem870 {
    public int[] advantageCount(int[] A, int[] B) {
        int[] answer = new int[A.length];
        Arrays.sort(A);
        Integer[][] b = new Integer[B.length][2];
        for (int i = 0; i < B.length; i++) {
            b[i][0] = i; // the index
            b[i][1] = B[i]; // the value
        }
        int right = A.length - 1;
        int left = 0;
        int j = B.length - 1;
        while (left <= right) {
            if (A[right] > b[right][1]) {
                answer[b[j][0]] = A[right];
                right--;
                j--;
            } else {
                answer[b[j][0]] = A[left];
                left++;
                j--;
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Problem870 prob = new Problem870();
        System.out.println(Arrays.toString(prob.advantageCount(new int[]{2, 7, 11, 15}, new int[]{1, 10, 4, 11}))); // [2,11,7,15]
        System.out.println(Arrays.toString(prob.advantageCount(new int[]{12, 24, 8, 32}, new int[]{13, 25, 32, 11}))); // [24,32,8,12]
        System.out.println(Arrays.toString(prob.advantageCount(new int[]{12, 19, 29, 46}, new int[]{10, 20, 30, 40}))); // [12,29,46,19]
    }
}

@@ -36,16 +36,45 @@
 .Arrays;
+%0Aimport java.util.Comparator;
 %0A%0A/**%0A *
@@ -447,32 +447,89 @@
 value%0A        %7D%0A
+        Arrays.sort(b, Comparator.comparing(x -%3E x%5B1%5D));%0A
         int righ
@@ -659,21 +659,17 @@
 ht%5D %3E b%5B
-right
+j
 %5D%5B1%5D) %7B%0A
@@ -737,37 +737,16 @@
 ight--;%0A
-                j--;%0A
         
@@ -841,16 +841,9 @@
     
-    j--;
+%7D
 %0A   
@@ -843,33 +843,36 @@
   %7D%0A            
-%7D
+j--;
 %0A        %7D%0A     
@@ -898,506 +898,7 @@
    %7D
-%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem870 prob = new Problem870();%0A        System.out.println(Arrays.toString(prob.advantageCount(new int%5B%5D%7B2, 7, 11, 15%7D, new int%5B%5D%7B1, 10, 4, 11%7D))); // %5B2,11,7,15%5D%0A        System.out.println(Arrays.toString(prob.advantageCount(new int%5B%5D%7B12, 24, 8, 32%7D, new int%5B%5D%7B13, 25, 32, 11%7D))); // %5B24,32,8,12%5D%0A        System.out.println(Arrays.toString(prob.advantageCount(new int%5B%5D%7B12, 19, 29, 46%7D, new int%5B%5D%7B10, 20, 30, 40%7D))); // %5B12,29,46,19%5D%0A    %7D
 %0A%7D%0A

Solve problem 870