LeetCode 题解工作台

划分技能点相等的团队

给你一个正整数数组 skill ,数组长度为 偶数 n ,其中 skill[i] 表示第 i 个玩家的技能点。将所有玩家分成 n / 2 个 2 人团队,使每一个团队的技能点之和 相等 。 团队的 化学反应 等于团队中玩家的技能点 乘积 。 返回所有团队的 化学反应 之和,如果无法使每个团队的技能点…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

要使得所有 人团队的技能点相等,最小值一定需要跟最大值匹配。因此,我们将数组 `skill` 排序,然后用双指针 和 分别指向数组的首位,两两匹配,判断其和是否均为同一个数。 若不是,说明技能点无法相等,直接返回 ,否则,将化学反应累加到答案中。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数数组 skill ,数组长度为 偶数 n ,其中 skill[i] 表示第 i 个玩家的技能点。将所有玩家分成 n / 22 人团队,使每一个团队的技能点之和 相等

团队的 化学反应 等于团队中玩家的技能点 乘积

返回所有团队的 化学反应 之和,如果无法使每个团队的技能点之和相等,则返回 -1

 

示例 1:

输入:skill = [3,2,5,1,3,4]
输出:22
解释:
将玩家分成 3 个团队 (1, 5), (2, 4), (3, 3) ,每个团队的技能点之和都是 6 。
所有团队的化学反应之和是 1 * 5 + 2 * 4 + 3 * 3 = 5 + 8 + 9 = 22 。

示例 2:

输入:skill = [3,4]
输出:12
解释:
两个玩家形成一个团队,技能点之和是 7 。
团队的化学反应是 3 * 4 = 12 。

示例 3:

输入:skill = [1,1,2,3]
输出:-1
解释:
无法将玩家分成每个团队技能点都相等的若干个 2 人团队。

 

提示:

  • 2 <= skill.length <= 105
  • skill.length 是偶数
  • 1 <= skill[i] <= 1000
lightbulb

解题思路

方法一:排序

要使得所有 22 人团队的技能点相等,最小值一定需要跟最大值匹配。因此,我们将数组 skill 排序,然后用双指针 iijj 分别指向数组的首位,两两匹配,判断其和是否均为同一个数。

若不是,说明技能点无法相等,直接返回 1-1,否则,将化学反应累加到答案中。

遍历结束,返回答案即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 是数组 skill 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def dividePlayers(self, skill: List[int]) -> int:
        skill.sort()
        t = skill[0] + skill[-1]
        i, j = 0, len(skill) - 1
        ans = 0
        while i < j:
            if skill[i] + skill[j] != t:
                return -1
            ans += skill[i] * skill[j]
            i, j = i + 1, j - 1
        return ans
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate correctly identifies that sorting is key to pairing players for equal skill teams.

  • question_mark

    The candidate applies a two-pointer technique effectively to match players into teams.

  • question_mark

    The candidate should mention checking for equal skill sums in all pairs before calculating chemistries.

warning

常见陷阱

外企场景
  • error

    Forgetting to sort the skill array before pairing, which would result in invalid teams.

  • error

    Not checking if all teams have the same total skill level before calculating chemistry.

  • error

    Mistaking the chemistry calculation (multiplying skills) as just adding the skills.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if there are constraints on the maximum team size?

  • arrow_right_alt

    How would the solution change if skill[i] could be zero or negative?

  • arrow_right_alt

    What if the problem required calculating chemistry for an odd number of players?

help

常见问题

外企场景

划分技能点相等的团队题解:数组·哈希·扫描 | LeetCode #2491 中等