---
title: "870. Advantage Shuffle"
url: "https://laigary.com/interview/coding/870-advantage-shuffle"
type: "note"
section: "coding"
date: "2024-08-14"
updated: "2024-08-14"
tags: ["Greedy", "Heap", "Two Pointers"]
---

# 870. Advantage Shuffle

[870\. Advantage Shuffle](https://leetcode.com/problems/advantage-shuffle/)

```python
class Solution:
    def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:
        
        n = len(nums1)
        nums1.sort()
        heap = []

        for i in range(len(nums2)):
            num = nums2[i]
            # Pytho 的 heap 是最小的在最上面，但是我們要的是最大的要在最上面。
            heapq.heappush(heap, (-num, i))

        left = 0
        right = n - 1
        res = [0] * n

        while heap:
            val, idx = heapq.heappop(heap)
            val = val * -1
            if val < nums1[right]:
                res[idx] = nums1[right]
                right -= 1
            else:
                res[idx] = nums1[left]
                left += 1
        return res
```
