LeetCode 题解工作台
Alice 和 Bob 玩鲜花游戏
Alice 和 Bob 在一片田野上玩一个回合制游戏,他们之间有两排花。Alice 和 Bob 之间第一排有 x 朵花,第二排有 y 朵花。 游戏过程如下: Alice 先行动。 每一次行动中,当前玩家必须选择其中一排,然后在这边摘一朵鲜花。 一次行动结束后,如果两排上都没有剩下鲜花,那么 当前 玩…
1
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数学·driven
答案摘要
根据题目描述,每一次行动,玩家都会选择顺时针或者逆时针方向,然后摘一朵鲜花。由于 Alice 先行动,因此当 $x + y$ 为奇数时,Alice 一定会赢得游戏。 因此,鲜花数目 和 满足以下条件:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
Alice 和 Bob 在一片田野上玩一个回合制游戏,他们之间有两排花。Alice 和 Bob 之间第一排有 x 朵花,第二排有 y 朵花。

游戏过程如下:
- Alice 先行动。
- 每一次行动中,当前玩家必须选择其中一排,然后在这边摘一朵鲜花。
- 一次行动结束后,如果两排上都没有剩下鲜花,那么 当前 玩家抓住对手并赢得游戏的胜利。
给你两个整数 n 和 m ,你的任务是求出满足以下条件的所有 (x, y) 对:
- 按照上述规则,Alice 必须赢得游戏。
- 第一排的鲜花数目
x必须在区间[1,n]之间。 - 第二排的鲜花数目
y必须在区间[1,m]之间。
请你返回满足题目描述的数对 (x, y) 的数目。
示例 1:
输入:n = 3, m = 2 输出:3 解释:以下数对满足题目要求:(1,2) ,(3,2) ,(2,1) 。
示例 2:
输入:n = 1, m = 1 输出:0 解释:没有数对满足题目要求。
提示:
1 <= n, m <= 105
解题思路
方法一:数学
根据题目描述,每一次行动,玩家都会选择顺时针或者逆时针方向,然后摘一朵鲜花。由于 Alice 先行动,因此当 为奇数时,Alice 一定会赢得游戏。
因此,鲜花数目 和 满足以下条件:
- 为奇数;
- ;
- 。
若 为奇数, 一定为偶数。此时 的取值个数为 , 的取值个数为 ,因此满足条件的数对个数为 。
若 为偶数, 一定为奇数。此时 的取值个数为 , 的取值个数为 ,因此满足条件的数对个数为 。
因此,满足条件的数对个数为 ,即 。
时间复杂度 ,空间复杂度 。
class Solution:
def flowerGame(self, n: int, m: int) -> int:
a1 = (n + 1) // 2
b1 = (m + 1) // 2
a2 = n // 2
b2 = m // 2
return a1 * b2 + a2 * b1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Problem-solving involves quick analysis of mathematical patterns.
- question_mark
Candidate demonstrates proficiency in math-driven algorithms.
- question_mark
Approach to parity analysis shows efficiency and optimization.
常见陷阱
外企场景- error
Overlooking the parity condition can lead to incorrect pair counting.
- error
Failing to optimize the counting approach could result in inefficient solutions for large inputs.
- error
Not understanding the circular nature of the field might complicate boundary conditions.
进阶变体
外企场景- arrow_right_alt
Consider different sizes of n and m to evaluate solution performance.
- arrow_right_alt
Explore edge cases such as the smallest values for n and m.
- arrow_right_alt
Examine how changes in the circular structure affect the solution for n and m.