LeetCode 题解工作台

优势洗牌

给定两个长度相等的数组 nums1 和 nums2 , nums1 相对于 nums2 的 优势 可以用满足 nums1[i] > nums2[i] 的索引 i 的数目来描述。 返回 nums1 的 任意 排列,使其相对于 nums2 的优势最大化。 示例 1: 输入: nums1 = [2,7,1…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 双·指针·invariant

bolt

答案摘要

类似田忌赛马。将 , 按照升序排列。然后遍历 中的每个元素 ,若在 中找不到比 小的,则将 与当前 中的最大元素匹配。 时间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定两个长度相等的数组 nums1 和 nums2nums1 相对于 nums2优势可以用满足 nums1[i] > nums2[i] 的索引 i 的数目来描述。

返回 nums1 的 任意 排列,使其相对于 nums2 的优势最大化。

 

示例 1:

输入:nums1 = [2,7,11,15], nums2 = [1,10,4,11]
输出:[2,11,7,15]

示例 2:

输入:nums1 = [12,24,8,32], nums2 = [13,25,32,11]
输出:[24,32,8,12]

 

提示:

  • 1 <= nums1.length <= 105
  • nums2.length == nums1.length
  • 0 <= nums1[i], nums2[i] <= 109
lightbulb

解题思路

方法一:贪心 + 排序

类似田忌赛马。将 nums1nums1, nums2nums2 按照升序排列。然后遍历 nums1nums1 中的每个元素 vv,若在 nums2[i..j]nums2[i..j] 中找不到比 vv 小的,则将 vv 与当前 nums2[i..j]nums2[i..j] 中的最大元素匹配。

时间复杂度 O(nlogn)O(nlogn)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1.sort()
        t = sorted((v, i) for i, v in enumerate(nums2))
        n = len(nums2)
        ans = [0] * n
        i, j = 0, n - 1
        for v in nums1:
            if v <= t[i][0]:
                ans[t[j][1]] = v
                j -= 1
            else:
                ans[t[i][1]] = v
                i += 1
        return ans
speed

复杂度分析

指标
时间O(N \log N)
空间O(N)
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect clarification on how to match nums1 elements to nums2 efficiently using sorting.

  • question_mark

    Be ready to explain why a naive greedy from largest to largest might fail on certain permutations.

  • question_mark

    Demonstrate understanding of invariant tracking during two-pointer scanning to preserve advantage counts.

warning

常见陷阱

外企场景
  • error

    Forgetting to preserve original indices of nums2 while sorting, leading to misaligned assignments.

  • error

    Assigning largest nums1 elements too early, wasting them on nums2 elements that could be beaten by smaller nums1.

  • error

    Failing to handle leftover nums1 elements correctly, which can reduce the overall advantage count.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute the minimum permutation of nums1 that still maximizes advantage instead of any permutation.

  • arrow_right_alt

    Apply the same two-pointer greedy pattern to a circular array variant where comparisons wrap around.

  • arrow_right_alt

    Change the condition to nums1[i] >= nums2[i] and adjust the greedy assignment accordingly.

help

常见问题

外企场景

优势洗牌题解:双·指针·invariant | LeetCode #870 中等