#870
Medium Algorithms Advantage shuffle
Array Two Pointers Greedy Sorting
54.3% acceptance
Feb 22, 2026
1691
101
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.
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn advantage_count(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let n = nums1.len();
let mut sorted1 = nums1.clone();
sorted1.sort_unstable();
let mut deq: std::collections::VecDeque<i32> = sorted1.into_iter().collect();
let mut idx2: Vec<usize> = (0..n).collect();
idx2.sort_unstable_by(|&a, &b| nums2[b].cmp(&nums2[a]));
let mut ans = vec![0; n];
for i in idx2 {
if *deq.back().unwrap() > nums2[i] {
ans[i] = deq.pop_back().unwrap();
} else {
ans[i] = deq.pop_front().unwrap();
}
}
ans
}
}