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 ofnums1 _that maximizes itsadvantage with
respect to _nums2.
The key idea is to maximize the number of positions where nums1[i] > nums2[i]. By sorting both arrays, we can always try to assign the smallest possible number from nums1 that is still greater than the current number in nums2. If no such number exists, we assign the smallest remaining number from nums1 (which can’t beat any remaining nums2).
classSolution {
public: vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
vector<int> ans(n);
vector<pair<int, int>> b;
for (int i =0; i < n; ++i) b.push_back({nums2[i], i});
sort(nums1.begin(), nums1.end());
sort(b.begin(), b.end());
int l =0, r = n -1;
for (int i = n -1; i >=0; --i) {
if (nums1[r] > b[i].first) {
ans[b[i].second] = nums1[r--];
} else {
ans[b[i].second] = nums1[l++];
}
}
return ans;
}
};
classSolution {
publicint[]advantageCount(int[] nums1, int[] nums2) {
int n = nums1.length;
int[] ans =newint[n];
int[][] b =newint[n][2];
for (int i = 0; i < n; ++i) {
b[i][0]= nums2[i];
b[i][1]= i;
}
Arrays.sort(nums1);
Arrays.sort(b, (a, c) -> Integer.compare(a[0], c[0]));
int l = 0, r = n - 1;
for (int i = n - 1; i >= 0; --i) {
if (nums1[r]> b[i][0]) {
ans[b[i][1]]= nums1[r--];
} else {
ans[b[i][1]]= nums1[l++];
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defadvantageCount(self, nums1: list[int], nums2: list[int]) -> list[int]:
n = len(nums1)
ans: list[int] = [0] * n
b: list[tuple[int, int]] = [(v, i) for i, v in enumerate(nums2)]
nums1.sort()
b.sort()
l, r =0, n -1for i in range(n -1, -1, -1):
if nums1[r] > b[i][0]:
ans[b[i][1]] = nums1[r]
r -=1else:
ans[b[i][1]] = nums1[l]
l +=1return ans