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 positions i
for which nums1[i] > nums2[i]
.
Return any permutation of nums1
that maximizes its advantage with respect to nums2
.
nums1
and nums2
?
1
to 10^5
.nums1
and nums2
?
0
to 10^9
.To maximize the advantage of nums1
over nums2
:
nums1[i] > nums2[i]
.nums1
that can beat nums2
’s current largest remaining element. If no such nums1
is found, assign it to the smallest remaining nums2
(these can be paired with any nums1
).nums2
and keep track of their original indices.nums1
.nums1
:
nums1
that is still greater than the current element in nums2
.nums1
with the smallest element in nums2
(i.e., nums1
cannot win here).Here’s the Java code implementing the strategy:
import java.util.Arrays;
import java.util.PriorityQueue;
public class AdvantageShuffle {
public int[] advantageCount(int[] nums1, int[] nums2) {
// Length of the arrays
int n = nums1.length;
// Sort nums1 to facilitate sorting logic
Arrays.sort(nums1);
// Generate pairs of (value, index) for nums2, then sort by value
int[][] nums2WithIndex = new int[n][2];
for (int i = 0; i < n; i++) {
nums2WithIndex[i][0] = nums2[i];
nums2WithIndex[i][1] = i;
}
Arrays.sort(nums2WithIndex, (a, b) -> Integer.compare(a[0], b[0]));
// Result array to hold the permutation of nums1
int[] result = new int[n];
// Two pointers to allocate numbers
int left = 0, right = n - 1;
// Use a for loop to process sorted nums1
for (int num : nums1) {
if (num > nums2WithIndex[left][0]) {
// If the current number can take advantage, place it in the result
result[nums2WithIndex[left][1]] = num;
left++;
} else {
// Otherwise, place it against the largest remaining number in nums2
result[nums2WithIndex[right][1]] = num;
right--;
}
}
return result;
}
public static void main(String[] args) {
AdvantageShuffle solution = new AdvantageShuffle();
int[] nums1 = {2,7,11,15};
int[] nums2 = {1,10,4,11};
System.out.println(Arrays.toString(solution.advantageCount(nums1, nums2))); // Expected output [2,11,7,15] or any permutation with maximum advantage.
}
}
nums1
and nums2WithIndex
: (O(n \log n))This approach ensures that we use a greedy method to maximize the advantage by making optimal pairing strategies.
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?