LeetCode 题解工作台

比赛中的配对次数

给你一个整数 n ,表示比赛中的队伍数。比赛遵循一种独特的赛制: 如果当前队伍数是 偶数 ,那么每支队伍都会与另一支队伍配对。总共进行 n / 2 场比赛,且产生 n / 2 支队伍进入下一轮。 如果当前队伍数为 奇数 ,那么将会随机轮空并晋级一支队伍,其余的队伍配对。总共进行 (n - 1) / …

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·结合·模拟

bolt

答案摘要

根据题目描述我们知道,一共有 支队伍,每一次的配对,都会淘汰一支队伍,所以配对次数就是淘汰的队伍数,即 $n - 1$。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·模拟 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 n ,表示比赛中的队伍数。比赛遵循一种独特的赛制:

  • 如果当前队伍数是 偶数 ,那么每支队伍都会与另一支队伍配对。总共进行 n / 2 场比赛,且产生 n / 2 支队伍进入下一轮。
  • 如果当前队伍数为 奇数 ,那么将会随机轮空并晋级一支队伍,其余的队伍配对。总共进行 (n - 1) / 2 场比赛,且产生 (n - 1) / 2 + 1 支队伍进入下一轮。

返回在比赛中进行的配对次数,直到决出获胜队伍为止。

 

示例 1:

输入:n = 7
输出:6
解释:比赛详情:
- 第 1 轮:队伍数 = 7 ,配对次数 = 3 ,4 支队伍晋级。
- 第 2 轮:队伍数 = 4 ,配对次数 = 2 ,2 支队伍晋级。
- 第 3 轮:队伍数 = 2 ,配对次数 = 1 ,决出 1 支获胜队伍。
总配对次数 = 3 + 2 + 1 = 6

示例 2:

输入:n = 14
输出:13
解释:比赛详情:
- 第 1 轮:队伍数 = 14 ,配对次数 = 7 ,7 支队伍晋级。
- 第 2 轮:队伍数 = 7 ,配对次数 = 3 ,4 支队伍晋级。 
- 第 3 轮:队伍数 = 4 ,配对次数 = 2 ,2 支队伍晋级。
- 第 4 轮:队伍数 = 2 ,配对次数 = 1 ,决出 1 支获胜队伍。
总配对次数 = 7 + 3 + 2 + 1 = 13

 

提示:

  • 1 <= n <= 200
lightbulb

解题思路

方法一:脑筋急转弯

根据题目描述我们知道,一共有 nn 支队伍,每一次的配对,都会淘汰一支队伍,所以配对次数就是淘汰的队伍数,即 n1n - 1

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def numberOfMatches(self, n: int) -> int:
        return n - 1
speed

复杂度分析

指标
时间complexity is O(1) because the total matches can be calculated directly using n - 1. Space complexity is O(1) as no additional structures are needed; only counters for matches and teams are used.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect the candidate to identify the elimination pattern quickly.

  • question_mark

    Watch for correct handling of odd numbers of teams in rounds.

  • question_mark

    Check whether the candidate recognizes the O(1) formula versus full simulation.

warning

常见陷阱

外企场景
  • error

    Forgetting that an odd team automatically advances, leading to off-by-one errors.

  • error

    Simulating unnecessarily without realizing total matches equal n - 1.

  • error

    Incorrectly summing matches when counting advancing teams in each round.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count total matches for a double-elimination tournament with similar pairing rules.

  • arrow_right_alt

    Compute total matches if the tournament allows random byes instead of fixed odd-team advancement.

  • arrow_right_alt

    Determine total rounds instead of matches while applying the same elimination pattern.

help

常见问题

外企场景

比赛中的配对次数题解:数学·结合·模拟 | LeetCode #1688 简单