Leetcode 870. Advantage Shuffle
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.
nums1 and nums2 unique?
The problem can be efficiently solved using a greedy approach with sorting:
nums1 in non-decreasing order.nums2 maintaining the original indices.nums1 can give an advantage over elements in nums2.nums2, and for each element, try to find the smallest element in nums1 that is greater.nums1 that can be used and the ones that cannot provide an advantage.Here’s the C++ code implementing the above strategy:
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
// Sort nums1
sort(nums1.begin(), nums1.end());
// Create a pair of (value, index) for nums2
vector<pair<int, int>> sorted_nums2(n);
for (int i = 0; i < n; i++) {
sorted_nums2[i] = {nums2[i], i};
}
// Sort nums2 based on the value
sort(sorted_nums2.begin(), sorted_nums2.end());
// Result array
vector<int> result(n);
// Two pointers for nums1
int left = 0, right = n - 1;
// Try to maximize advantage
for (int i = 0; i < n; i++) {
if (nums1[left] > sorted_nums2[i].first) {
result[sorted_nums2[i].second] = nums1[left++];
} else {
result[sorted_nums2[i].second] = nums1[right--];
}
}
return result;
}
nums1: (O(n \log n))nums2: (O(n \log n))nums2 with two pointers: (O(n))The overall time complexity is dominated by the sorting steps: [ O(n \log n) + O(n \log n) + O(n) = O(n \log n) ]
This is efficient for the given problem constraints and provides an optimal solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?