Advantage Shuffle Problem
Description
LeetCode Problem 870.
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].
Return any permutation of nums1 that maximizes its advantage with respect to nums2.
Example 1:
1
2
Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11]
Output: [2,11,7,15]
Example 2:
1
2
Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11]
Output: [24,32,8,12]
Constraints:
- 1 <= nums1.length <= 10^5
- nums2.length == nums1.length
- 0 <= nums1[i], nums2[i] <= 10^9
Sample C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<int> advantageCount(vector<int>& A, vector<int>& B) {
int n = A.size();
if (n < 2) return A;
sort(A.begin(), A.end());
vector<pair<int,int>> C;
for (int i = 0; i < n; ++i)
C.push_back(make_pair(B[i], i));
sort(C.begin(), C.end());
int l = 0, r = n-1;
vector<int> D(n);
for (int i = n-1; i >= 0; i--) {
if (A[r] <= C[i].first)
D[C[i].second] = A[l++];
else
D[C[i].second] = A[r--];
}
return D;
}
};