Skip to content

870. Advantage Shuffle 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
    multiset<int> set{nums1.begin(), nums1.end()};

    for (int i = 0; i < nums2.size(); ++i) {
      const auto p =
          *set.rbegin() <= nums2[i] ? set.begin() : set.upper_bound(nums2[i]);
      nums1[i] = *p;
      set.erase(p);
    }

    return nums1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int[] advantageCount(int[] nums1, int[] nums2) {
    TreeMap<Integer, Integer> map = new TreeMap<>();

    for (final int num : nums1)
      map.merge(num, 1, Integer::sum);

    for (int i = 0; i < nums2.length; i++) {
      Integer key = map.higherKey(nums2[i]);
      if (key == null)
        key = map.firstKey();
      if (map.merge(key, -1, Integer::sum) == 0)
        map.remove(key);
      nums1[i] = key;
    }

    return nums1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from sortedcontainers import SortedList


class Solution:
  def advantageCount(self, nums1: list[int], nums2: list[int]) -> list[int]:
    sl = SortedList(nums1)

    for i, num in enumerate(nums2):
      index = 0 if sl[-1] <= num else sl.bisect_right(num)
      nums1[i] = sl[index]
      del sl[index]

    return nums1