Advantage Shuffle LT870

Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i].

Return any permutation of A that maximizes its advantage with respect to B.


Example 1:

Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15]

Example 2:

Input: A = [12,24,8,32], B = [13,25,32,11]
Output: [24,32,8,12]

Note:

  1. 1 <= A.length = B.length <= 10000
  2. 0 <= A[i] <= 10^9
  3. 0 <= B[i] <= 10^9

 Idea 1. Take adavantage of TreeMap to find the smallest key which is strictly bigger than the given value, for each value in the array, find the least bigger value, if no bigger value, take the smallest element.

Time complexity: O(nlogn)

Space complexity: O(n)

 1 class Solution {
 2     public int[] advantageCount(int[] A, int[] B) {
 3         TreeMap<Integer, Integer> intCnt = new TreeMap<>();
 4         for(int a: A) {
 5             intCnt.put(a, intCnt.getOrDefault(a, 0) + 1);
 6         }
 7         
 8         int[] result = new int[A.length];
 9         for(int i = 0; i < B.length; ++i) {
10             
11             Integer candidate = intCnt.higherKey(B[i]);
12             if(candidate == null) {
13                 candidate = intCnt.firstKey();
14             }
15             result[i] = candidate;
16             intCnt.put(candidate, intCnt.get(candidate)-1);
17             if(intCnt.get(candidate) == 0) {
18                 intCnt.remove(candidate);
19             }
20         }
21         
22         return result;
23     }
24 }

Idea 1.b 田忌赛马 use prority queue to store(value, index) for max in sorted order, if max[A] > max[B], put result[pos[maxB]] = A, otherwise result[pos[maxB]] = min[A], if max[A] can't satisfy mx[B], no other values can, min[A] is the most cost-effective choice.

Time complexity: O(nlogn)

扫描二维码关注公众号,回复: 6093250 查看本文章

Space complexity: O(n)

 1 class Solution {
 2     public int[] advantageCount(int[] A, int[] B) {
 3         
 4         PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
 5             (int[] a, int[] b) -> {
 6                 return Integer.compare(b[0], a[0]);
 7             });
 8         
 9         for(int i = 0; i < B.length; ++i) {
10             maxHeap.add(new int[] {B[i], i});
11         }
12         
13         Arrays.sort(A);
14         int[] result = new int[A.length];
15         
16         int minIndex = 0, maxIndex = A.length-1;
17         while(!maxHeap.isEmpty()) {
18             int[] curr = maxHeap.poll();
19             if(A[maxIndex] > curr[0]) {
20                 result[curr[1]] = A[maxIndex--];
21             }
22             else {
23                 result[curr[1]] = A[minIndex++];
24             }
25         }
26         
27         return result;
28     }
29 }

猜你喜欢

转载自www.cnblogs.com/taste-it-own-it-love-it/p/10801560.html